1、未使用 CountDownLatch
public class TestCountDownLatch {
public static void main(String[] args) throws InterruptedException {
TestCountDown testCountDown = new TestCountDown();
Thread threadA = new Thread(testCountDown);
Thread threadB = new Thread(testCountDown);
Thread threadC = new Thread(testCountDown);
Thread threadD = new Thread(testCountDown);
Thread threadE = new Thread(testCountDown);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
threadE.start();
System.out.println("全部执行完");
}
public static class TestCountDown implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
System.out.println("线程:" + Thread.currentThread().getName() + "执行完!");
}
}
}
结果
子线程还没执行完,主线程就先执行完了
2、使用 CountDownLatch
public class TestCountDownLatch {
public static CountDownLatch countDownLatch = new CountDownLatch(5);
public static void main(String[] args) throws InterruptedException {
TestCountDown testCountDown = new TestCountDown();
Thread threadA = new Thread(testCountDown);
Thread threadB = new Thread(testCountDown);
Thread threadC = new Thread(testCountDown);
Thread threadD = new Thread(testCountDown);
Thread threadE = new Thread(testCountDown);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
threadE.start();
countDownLatch.await();
System.out.println("全部执行完");
}
public static class TestCountDown implements Runnable{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
System.out.println("线程:" + Thread.currentThread().getName() + "执行完!");
countDownLatch.countDown();
}
}
}
结果
等待子线程全部执行完,主线程才执行完毕