多线程有一套标准实现,具体哪种好要经过压测来决定。

变量在线程里访问没问题,但是s放到类下面就会有访问问题(变成多个线程访问同一变量)

  1. public class TicketSeller4 {
  2. static Queue<String> tickets = new ConcurrentLinkedQueue<>();
  3. // static String s = null;
  4. static {
  5. for(int i=0; i<1000; i++) tickets.add("票 编号:" + i);
  6. }
  7. public static void main(String[] args) {
  8. for(int i=0; i<10; i++) {
  9. new Thread(()->{
  10. while(true) {
  11. String s = tickets.poll();
  12. if(s == null) break;
  13. else System.out.println("销售了--" + s);
  14. }
  15. }).start();
  16. }
  17. }
  18. }