Java并发编程工具之countdownlatch示例

countdownlatch允许一个或多个线程等待其他线程的完成。

例如以下代码,输出的结果不是固定的,有可能是312,也有可能是123,因为main线程和new thread线程会由系统调度执行,不一定是有序的。

public class CountDownLatchExample1 {

    public static void main(String[] args) throws InterruptedException{

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(1);
                
                System.out.println(2);
              
            }
        }).start();
      
        System.out.println(3);
    }
}
加入countdownlatch之后,main线程会等待new thread执行完成之后再执行。
public class CountDownLatchExample1 {

    public static void main(String[] args) throws InterruptedException{
        CountDownLatch c = new CountDownLatch(2);
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(1);
                c.countDown();
                System.out.println(2);
                c.countDown();
            }
        }).start();
        c.await();
        System.out.println(3);
    }
}

猜你喜欢

转载自blog.csdn.net/u010372981/article/details/80906956