CountDownLatch latch = new CountDownLatch(OFFICER_SIZE);//初始化计数器
latch.countDown();//计数器减一
latch.await();// 等待计数器为零
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LatchDemo {
public static final int OFFICER_SIZE = 80;// 0000000;
public static final int COMMON_PEOPLE_SIZE = 20;
public static void main(String[] args) {
ExecutorService exeuctor = Executors.newCachedThreadPool();
// must share the single latch
CountDownLatch latch = new CountDownLatch(OFFICER_SIZE);
System.out.println("the building is fire!");
for (int i = 0; i < COMMON_PEOPLE_SIZE; i++) {
exeuctor.execute(new commonPeople(i, latch));
}
for (int i = 0; i < OFFICER_SIZE; i++) {
exeuctor.execute(new officer(i, latch));
}
exeuctor.shutdown();
}
static class officer implements Runnable {
private int id;
private CountDownLatch latch;
public officer(int id, CountDownLatch latch) {
this.id = id;
this.latch = latch;
}
@Override
public void run() {
goOut();
latch.countDown();
}
private void goOut() {
System.out.println("I must go firstly when fire! my id:" + id);
}
}
static class commonPeople implements Runnable {
private int id;
private CountDownLatch latch;
public commonPeople(int id, CountDownLatch latch) {
this.id = id;
this.latch = latch;
}
@Override
public void run() {
try {
latch.await();
goOut();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void goOut() {
System.out.println("I am common people! my id:" + id);
}
}
}