主线程:
//Main主线程
publicclass
MainThread {
publicstatic
void
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));
}
}
子线程:
//子线程
publicclass
SubThread extendsThread{
//子线程记数器,记载着运行的线程数
privateCountDownLatch
runningThreadNum;
publicSubThread(CountDownLatch
runningThreadNum){
this.runningThreadNum
= runningThreadNum;
}
@Override
publicvoid
run() {
System.out.println(Thread.currentThread().getName()+"-start");
System.out.println(Thread.currentThread().getName()+"-do
something");
System.out.println(Thread.currentThread().getName()+"-end");
runningThreadNum.countDown();//正在运行的线程数减一
}
}