Java主线程等待子线程执行完毕-CountDownLatch

 

主线程:

 

//Main主线程
publicclassMainThread { 
 
    publicstaticvoid main(String[] args) throwsInterruptedException { 
        longstartTime = System.currentTimeMillis(); 
        intthreadNum = 5;//线程数
        //定义正在运行的线程数
        CountDownLatch runningThreadNum = newCountDownLatch(threadNum);
        System.out.println(Thread.currentThread().getName()+"-start");
        //创建多个子线程
        for(inti = 0; i < threadNum; i++) { 
            newSubThread(runningThreadNum).start();
        }
        //等待子线程都执行完了再执行主线程剩下的动作
        runningThreadNum.await();
        System.out.println(Thread.currentThread().getName()+"-end");
        longendTime = System.currentTimeMillis(); 
        System.out.println("runningTime:"+(endTime-startTime));
    }
}


 

子线程:

//子线程
publicclassSubThread extendsThread{
 
    //子线程记数器,记载着运行的线程数
    privateCountDownLatch runningThreadNum; 
 
    publicSubThread(CountDownLatch runningThreadNum){ 
        this.runningThreadNum = runningThreadNum; 
    }
     
    @Override
    publicvoidrun() { 
        System.out.println(Thread.currentThread().getName()+"-start");
        System.out.println(Thread.currentThread().getName()+"-do something");
        System.out.println(Thread.currentThread().getName()+"-end");
        runningThreadNum.countDown();//正在运行的线程数减一
    }
}


 

过往记忆 CSDN认证博客专家 过往记忆大数据 大数据 iteblog
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页