Java:多线程-等待/通知所有问题
我有一个类,它生成一堆线程,并且必须等待所有生成的线程完成。 (我需要计算所有线程完成的时间)。
MainClass 生成所有线程,然后在调用自身完成之前检查所有线程是否已完成。
这个逻辑行得通吗?如果是这样,有更好的方法吗?如果没有,我想更好地理解这个场景。
class MainClass{
private boolean isCompleted;
...
for(task : tasks){
threadpool.execute(task);
}
for(task : tasks){
if(!task.isCompleted()){
task.wait()
}
}
isCompleted = true;
}
class Task{
public void run(){
....
....
synchronized(this){
task.completed = true;
notifyAll();
}
}
}
I have a class which spawns a bunch of threads and have to wait till all the spawned threads are completed. ( I need to calculate the time for all threads to complete).
The MainClass spawns all the threads and then it checks whether all the threads are completed before it can call itself completed.
Will this logic work. If so, is there a better way to do this? If not , I would like to better understand this scenario.
class MainClass{
private boolean isCompleted;
...
for(task : tasks){
threadpool.execute(task);
}
for(task : tasks){
if(!task.isCompleted()){
task.wait()
}
}
isCompleted = true;
}
class Task{
public void run(){
....
....
synchronized(this){
task.completed = true;
notifyAll();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
notifyAll()
相对较慢。更好的方法是使用 CountDownLatch:notifyAll()
is relatively slow. A better way is to useCountDownLatch
:在这种情况下不需要等待/通知。您只需循环遍历线程并调用 join() 即可。如果线程已经完成,MainClass 线程将等待下一个线程。
您可能还想查看 java.util.concurrent 包中的更高级别的实用程序。
There's no need for wait/notify in this case. You can just loop through the threads and call
join()
. If the thread's already finished, the MainClass thread will just wait for the next one.You might want to have a look at the higher-level utilities in the
java.util.concurrent
package too.这一切都可以通过java.util.concurrent.ExecutorService来完成。
就是这样。
All this can be done by java.util.concurrent.ExecutorService.
That's about it.