所有線程執行完再執行主線程案例

一、案例代碼

 //計數器
        CountDownLatch countDownLatch = new CountDownLatch(2);

        //執行線程1
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + ",子行程開始執行。。。");
            //計數器減1
            countDownLatch.countDown();
            System.out.println(Thread.currentThread().getName() + ",子行程執行結束。。。");
        }).start();
        //執行線程1
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + ",子行程開始執行。。。");
            //計數器減1
            countDownLatch.countDown();
            System.out.println(Thread.currentThread().getName() + ",子行程執行結束。。。");
        }).start();
        //減去爲0,恢復任務繼續執行
        countDownLatch.await();
        System.out.println("兩個子線程執行完畢....");
        System.out.println("主線程繼續執行.....");
        for (int i = 0; i <10; i++) {
            System.out.println("main,i:"+i);
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章