同時:CountDownLatchの使用
1920 ワード
CountDownLatch:他のスレッドで実行されている操作のセットを完了する前に、1つ以上のスレッドを待機させる同期支援クラス.CyclicBarrierとよく似ています.しかし、CountDownLatchのカウンタは一度しか使用できませんが、CyclicBarrierはリサイクルできます.主な方法public CountDownLatch(int count);public void countDown(); public void await()throws InterruptedExceptionの例(「Think In Java」から、少し変更):latchに注意.await()の位置
出力:
11 completed!
7 completed!
9 completed!
10 completed!
5 completed!
8 completed!
12 completed!
1 completed!
2 completed!
6 completed!
4 completed!
0 completed!
3 completed!
Launched all tasks
class TaskPortion implements Runnable{
private static int counter = 0;
private final int id = counter++;
private static Random rand = new Random(47);
private final CountDownLatch latch;
TaskPortion(CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
try {
doWork();
latch.countDown();
// latch.await(); , CountDownLatch
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void doWork() throws InterruptedException{
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
System.out.println(this + "completed!");
}
public String toString(){
return String.format("%1$-3d", id);
}
}
public class CountDownLatchDemo {
static final int SIZE = 13;
public static void main(String[] args) throws InterruptedException{
ExecutorService exec = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(SIZE);
for(int i = 0; i < SIZE; i++){
exec.execute(new TaskPortion(latch));
}
latch.await();//
System.out.println("Launched all tasks");
exec.shutdown();
}
}
出力:
11 completed!
7 completed!
9 completed!
10 completed!
5 completed!
8 completed!
12 completed!
1 completed!
2 completed!
6 completed!
4 completed!
0 completed!
3 completed!
Launched all tasks