天涯尽头无女友
楼上的解释完全正确,不过可以利用s.poll()返回值是否为null,作为跳出条件。下面诗完整代码。packagecom.demo;importjava.util.ArrayList;importjava.util.Random;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingQueue;classConsumerimplementsRunnable{privateStringname;privateBlockingQueues=null;publicConsumer(Stringname,BlockingQueues){this.name=name;this.s=s;}publicvoidrun(){try{while(true){Stringproduct=s.poll();if(product==null){break;}intt=(newRandom()).nextInt(10);System.out.println(name+"消费("+product+").");System.out.println(name+"====sleep"+t+"secs====");Thread.sleep(t*1000);}}catch(InterruptedExceptione){e.printStackTrace();}}}publicclassHelloJava8{publicstaticvoidmain(String[]args)throwsInterruptedException{BlockingQueues=newLinkedBlockingQueue();s.put("java");s.put("python");s.put("php");s.put("c++");s.put("c");ArrayListthreadList=newArrayList();Threadt1=newThread(newConsumer("zhangsan",s));t1.start();threadList.add(t1);Threadt2=newThread(newConsumer("lisi",s));t2.start();threadList.add(t2);Threadt3=newThread(newConsumer("wangwu",s));t3.start();threadList.add(t3);Threadt4=newThread(newConsumer("afei",s));t4.start();threadList.add(t4);Threadt5=newThread(newConsumer("jb",s));t5.start();threadList.add(t5);for(Threadthread:threadList){thread.join();}System.out.println("主线程执行完毕");}}