使用Java多線程編程時經常遇到主線程需要等待子線程執行完成以後才能繼續執行,那麼接下來介紹一種簡單的方式使主線程等待。
java.util.concurrent.CountDownLatch
使用countDownLatch.await()方法非常簡單的完成主線程的等待:
public class ThreadWait {
public static void main(String[] args) throws InterruptedException {
int threadNumber = 10;
final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
for (int i = 0; i < threadNumber; i++) {
final int threadID = i;
new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("threadID:[%s] finished!!", threadID));
countDownLatch.countDown();
}
}.start();
}
countDownLatch.await();
System.out.println("main thread finished!!");
}
}