import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class Demo03 {
public static void main(String[] args) {
final Queue<String> queue = new ConcurrentLinkedQueue<String>();
queue.add("11111111111");
queue.add("22222222222");
queue.add("33333333333");
queue.add("44444444444444");
queue.add("555555555555555");
queue.add("666666666666666");
queue.add("7777777777777");
for(int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (queue.size() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = queue.poll();
if(value != "" && null != value)
System.out.println(Thread.currentThread().getName() + "------------ " + value);
}
}
}).start();
}
}
}
输出为:
Thread-3------------ 11111111111
Thread-2------------ 22222222222
Thread-4------------ 44444444444444
Thread-0------------ 555555555555555
Thread-1------------ 33333333333
Thread-2------------ 666666666666666
Thread-3------------ 7777777777777
一种是将所以的线程放在一个线程池中,另一种是使用闭锁的方式,计数器,当计数器为0的时候,表示所以的线程都已经执行完成!