CountDownLatchの使用(カウントダウンカウンタ)
2149 ワード
countDown()カウンタを1つ減らします
await()待機カウンタ値は0で、0に達するとすべての待機者が実行を開始します
await()待機カウンタ値は0で、0に達するとすべての待機者が実行を開始します
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountdownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for(int i=0;i<3;i++){
Runnable runnable = new Runnable(){
public void run(){
try {
System.out.println(" " + Thread.currentThread().getName() +
" ");
cdOrder.await();
System.out.println(" " + Thread.currentThread().getName() +
" ");
Thread.sleep((long)(Math.random()*10000));
System.out.println(" " + Thread.currentThread().getName() +
" ");
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println(" " + Thread.currentThread().getName() +
" ");
cdOrder.countDown();
System.out.println(" " + Thread.currentThread().getName() +
" , ");
cdAnswer.await();
System.out.println(" " + Thread.currentThread().getName() +
" ");
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}