您的位置:首页 > 其它

主线程等待所有子线程完成后再执行

2017-06-07 14:42 411 查看
public class WaitThread {
public static Lock lock = new ReentrantLock();

public static void main(String[] args) throws InterruptedException {
long time1 = System.currentTimeMillis();
CountDownLatch countDownLatch = new CountDownLatch(10);
for (int i = 0;i<10;i++){
Thread thread = new Thread(new MyThread(countDownLatch));
thread.start();
}
countDownLatch.await();//等待所有子线程执行完
long time2 = System.currentTimeMillis();
System.out.println("花费时间:"+(time2-time1));
System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记
}
}

class MyThread implements Runnable{

private CountDownLatch countDownLatch;
public MyThread(){}
public MyThread(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}

@Override
public void run() {
WaitThread.lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "开始...");
//Do somethings
countDownLatch.countDown();//线程结束时计数器减1
System.out.println(Thread.currentThread().getName() + "结束. 还有" + countDownLatch.getCount() + " 个线程");
}finally {
WaitThread.lock.unlock();
}
}
}


执行结果:

Thread-0开始…

Thread-0结束. 还有9 个线程

Thread-7开始…

Thread-7结束. 还有8 个线程

Thread-1开始…

Thread-1结束. 还有7 个线程

Thread-2开始…

Thread-2结束. 还有6 个线程

Thread-3开始…

Thread-3结束. 还有5 个线程

Thread-4开始…

Thread-4结束. 还有4 个线程

Thread-5开始…

Thread-5结束. 还有3 个线程

Thread-6开始…

Thread-6结束. 还有2 个线程

Thread-8开始…

Thread-8结束. 还有1 个线程

Thread-9开始…

Thread-9结束. 还有0 个线程

花费时间:6

main结束.

public class WaitThread {
public static Lock lock = new ReentrantLock();

public static void main(String[] args) throws InterruptedException {
ExecutorService exe = Executors.newFixedThreadPool(10);
long time1 = System.currentTimeMillis();
for (int i = 1; i <= 10; i++) {
exe.execute(new MyThread());
}
exe.shutdown();//关闭线程池,不会真的关闭,只是不接收新任务
while (true) {
//判断是否所有线程都执行完毕
if (exe.isTerminated()) {
System.out.println("结束了!");
long time2 = System.currentTimeMillis();
System.out.println("花费时间:"+(time2-time1));
break;
}
Thread.sleep(20);//防止循环很多次
}
}
}

class MyThread implements Runnable{

@Override
public void run() {
WaitThread.lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "开始...");

System.out.println(Thread.currentThread().getName() + "结束.");
}finally {
WaitThread.lock.unlock();
}
}
}


执行结果:

pool-1-thread-1开始…

pool-1-thread-1结束.

pool-1-thread-2开始…

pool-1-thread-2结束.

pool-1-thread-4开始…

pool-1-thread-4结束.

pool-1-thread-3开始…

pool-1-thread-3结束.

pool-1-thread-5开始…

pool-1-thread-5结束.

pool-1-thread-6开始…

pool-1-thread-6结束.

pool-1-thread-7开始…

pool-1-thread-7结束.

pool-1-thread-10开始…

pool-1-thread-10结束.

pool-1-thread-9开始…

pool-1-thread-9结束.

pool-1-thread-8开始…

pool-1-thread-8结束.

结束了!

花费时间:23
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程