JAVA并发CountDownLatch

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vmaps/article/details/80419972

两个任务不同的线程,执行完成等待
public class Test {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(2);

     new Thread(){
         public void run() {
             try {
                 System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                Thread.sleep(3000);
                System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         };
     }.start();

     new Thread(){
         public void run() {
             try {
                 System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                 Thread.sleep(3000);
                 System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                 latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         };
     }.start();

     try {
         System.out.println("等待2个子线程执行完毕...");
        latch.await();
        System.out.println("2个子线程已经执行完毕");
        System.out.println("继续执行主线程");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
 }
}

猜你喜欢

转载自blog.csdn.net/vmaps/article/details/80419972