java線程--倒計時器CountDownLatch

倒計時器CountDownLatch使用個例

public class Test {
    static final CountDownLatch end = new CountDownLatch(10);

    static class CounDownLatchDemo implements Runnable {

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println("check complete");
                end.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        CounDownLatchDemo demo = new CounDownLatchDemo();
        ExecutorService exs = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            exs.submit(demo);
        }
        try {
            // 等待全部任務結束完畢,再繼續執行主線程
            end.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Fire!");
        exs.shutdown();
    }

}
相關文章
相關標籤/搜索