java 线程池 等待_Java主线程等待子线程、线程池 | 学步园

publicclassTestThreadextendsThread

{

publicvoidrun()

{

System.out.println(this.getName() +"子线程开始");

try

{

// 子线程休眠五秒

Thread.sleep(5000);

}

catch(InterruptedException e)

{

e.printStackTrace();

}

System.out.println(this.getName() +"子线程结束");

}

}

首先是一个线程,它执行完成需要5秒。

1、主线程等待一个子线程

publicclassMain

{

publicstaticvoidmain(String[] args)

{

longstart = System.currentTimeMillis();

Thread thread = newTestThread();

thread.start();

longend = System.currentTimeMillis();

System.out.println("子线程执行时长:"+ (end - start));

}

}

在主线程中,需要等待子线程执行完成。但是执行上面的main发现并不是想要的结果:

子线程执行时长:0

Thread-0子线程开始

Thread-0子线程结束

很明显主线程和子线程是并发执行的,主线程并没有等待。

对于只有一个子线程,如果主线程需要等待子线程执行完成,再继续向下执行,可以使用Thread的join()方法。join()方法会阻塞主线程继续向下执行。

publicclassMain

{

publicstaticvoidmain(String[] args)

{

longstart = System.currentTimeMillis();

Thread thread = newTestThread();

thread.start();

try

{

thread.join();

}

catch(InterruptedException e)

{

e.printStackTrace();

}

longend = System.currentTimeMillis();

System.out.println("子线程执行时长:"+ (end - start));

}

}

执行结果:

Thread-0子线程开始

Thread-0子线程结束

子线程执行时长:5000

注意:join()要在start()方法之后调用。

2、主线程等待多个子线程

比如主线程需要等待5个子线程。这5个线程之间是并发执行。

publicclassMain

{

publicstaticvoidmain(String[] args)

{

longstart = System.currentTimeMillis();

for(inti =0; i <5; i++)

{

Thread thread = newTestThread();

thread.start();

try

{

thread.join();

}

catch(InterruptedException e)

{

e.printStackTrace();

}

}

longend = System.currentTimeMillis();

System.out.println("子线程执行时长:"+ (end - start));

}

}

在上面的代码套上一个for循环,执行结果:

Thread-0子线程开始

Thread-0子线程结束

Thread-1子线程开始

Thread-1子线程结束

Thread-2子线程开始

Thread-2子线程结束

Thread-3子线程开始

Thread-3子线程结束

Thread-4子线程开始

Thread-4子线程结束

子线程执行时长:25000

由于thread.join()阻塞了主线程继续执行,导致for循环一次就需要等待一个子线程执行完成,而下一个子线程不能立即start(),5个子线程不能并发。

要想子线程之间能并发执行,那么需要在所有子线程start()后,在执行所有子线程的join()方法。

publicclassMain

{

publicstaticvoidmain(String[] args)

{

longstart = System.currentTimeMillis();

List list = newArrayList();

for(inti =0; i <5; i++)

{

Thread thread = newTestThread();

thread.start();

list.add(thread);

}

try

{

for(Thread thread : list)

{

thread.join();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值