CountDownLatch

 

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestCountDownLatch {

public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
// 开始的倒数锁
final CountDownLatch begin = new CountDownLatch(1);
// 结束的倒数锁
final CountDownLatch end = new CountDownLatch(10000);
List<String> list=new ArrayList<String>();
// 十名选手
final ExecutorService exec = Executors.newFixedThreadPool(10);
for (int index = 0; index < 10000; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
begin.await();
System.out.println(NO);
String temp="AA"+NO;
list.add(temp);
Thread.sleep((long) (Math.random() * 10));
} catch (InterruptedException e) {
} finally {
end.countDown();
}
}
};
System.out.println(run);
exec.submit(run);
}
System.out.println("Game Start");
begin.countDown();
end.await();
System.out.println("Game Over");
exec.shutdown();
System.out.println("num:"+list.size());
// for(String s:list){
// System.out.println("数据打印:"+s);
// }
System.out.print("共计用时 ");
System.out.println(System.currentTimeMillis() - start);
}
}

 

posted @ 2018-09-12 17:23  暗渡陈仓xy  阅读(124)  评论(0编辑  收藏  举报