countDownLatchのテスト

5618 ワード

        package com.neusoft;

import java.util.concurrent.CountDownLatch;

/**
 *  , , , 。
 * CountDownLatch  join 
 * @author Administrator
 */
public class TestCountDownLatch {
    static CountDownLatch countDownLatch = new CountDownLatch(2);

    static Thread firstThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("first thread count down");
            countDownLatch.countDown();
        }
    });
    static Thread secondThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("second thread count down");
            countDownLatch.countDown();
        }
    });
    public static void main(String[] args) {
        firstThread.start();
        secondThread.start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main thread run");
    }
}
      

出力:
        first thread count down
second thread count down
main thread run
      

await()を削除
        main thread run
second thread count down
first thread count down