使用 Java的concurrent包裏面的CountDownLatch是一個非常實用的多線程控制工具類,其實可以把它看作一個計數器,只不過這個計數器的操作是原子操作,同時只能有一個線程去操作這個計數器,也就是同時只能有一個線程去減這個計數器裏面的值。 public CountDownLatch(int count) 構造器,實例化一個倒計時器,count指定計數個數 public void countDown() //計數減1 public void await() throws InterruptedException //阻塞等待直到計數器中的個數爲0或者線程中斷 public boolean await(long timeout, TimeUnit unit) //阻塞等待直到計數器的個數減爲0,或者線程中斷,或者等待了指定超時時間之後 public long getCount() //獲取計數器當前的數量
Demo
public class CountDownLatchTest implements Runnable{
static final CountDownLatch end = new CountDownLatch(10);
static final CountDownLatchTest demo =new CountDownLatchTest();
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(10)*1000);
System.out.println("check complete "+Thread.currentThread().getName());
end.countDown(); //計數器減1
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10 ; i++)
executor.submit(demo);
try {
end.await();
System.out.println("Fire!");
executor.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}