java等待线程结束,如何等待线程在Java中完成执行?

这篇博客探讨了如何在Java中使用线程进行并发计算。作者通过创建并启动线程来执行计算任务,并展示了如何利用isAlive()和join()方法等待所有线程完成,以确保在所有计算结束后继续执行主线程的代码。
摘要由CSDN通过智能技术生成

I have a few calculations that I'm spawning off into new threads then when all these calculations are complete I want to continue my execution.

Here's some mock up code that is similar to what I want to achieve without all the specifics,

public void calculation1(){

Thread thread = new Thread(){

public void run(){

/* do calculation */

};

};

}

public void calculation2(){

Thread thread = new Thread(){

public void run(){

/* do some other calculation */

};

};

}

calculation1();

calculation2();

/* Wait here until calculation1() and calculation2() complete */

/* Continue execution */

What's the best way for me to do this??

解决方案

Something like this:

public Thread calculation1(){

Thread thread = new Thread(){

public void run(){

/* do calculation */

}

};

thread.start();

return thread;

}

public Thread calculation2(){

Thread thread = new Thread(){

public void run(){

/* do some other calculation */

};

};

thread.start();

return thread;

}

And then use isAlive() and join() to wait for execution to finish

List threads = new ArrayList();

threads.add(calculation1());

threads.add(calculation2());

for(Thread t : threads){

if(t.isAlive()){

t.join();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值