天天看點

java 多線程 CountDownLatch

CountDownLatch能夠實作線程之間的等待,CountDownLatch一般用于某個線程A等待若幹個其他線程執行完任務之後,它才執行 

public class MyTest {

    public static void main(String[] args) {

        CountDownLatch count = new CountDownLatch(2);

        new Thread(){
            @Override
            public void run() {
                System.out.println(this.getName()+"開始執行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(this.getName()+"執行結束");
                 count.countDown();
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                System.out.println(this.getName()+"開始執行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(this.getName()+"執行結束");
                //
                count.countDown();
            }
        }.start();

        try {
            System.out.println("等待另外兩個線程執行結束");
            count.await();//直到計數器為 O 的時候才會執行後面的代碼
            System.out.println("另外兩個線程執行結束,執行count.await後面的方法");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}
           
java 多線程 CountDownLatch