public class CountDownExample {
static CountDownLatch countDownLatch = new CountDownLatch(3);
static class Thread1 extends Thread{
@Override
public void run(){
//干活
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//我干完活了
countDownLatch.countDown();
}
}
static class Thread2 extends Thread{
@Override
public void run(){
//干活
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//我干完活了
countDownLatch.countDown();
}
}
static class Thread3 extends Thread{
@Override
public void run(){
//干活
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//我干完活了
countDownLatch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
t2.start();
Thread3 t3 = new Thread3();
t3.start();
countDownLatch.await(); // 阻塞main线程
System.out.println("所有线程执行结束");
}
}
JUC-CountDownLatch示例
最新推荐文章于 2024-08-16 23:08:28 发布