等到所有线程完成他们在java中的工作 [英] wait until all threads finish their work in java
本文介绍了等到所有线程完成他们在java中的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个有5个线程的应用程序,它可以同时从Web获取一些信息并填充缓冲类中的5个不同字段。
我需要验证缓冲区数据并将其存储在数据库中所有线程都完成了他们的工作。
如何做到这一点(当所有线程完成工作时收到警报)?
I'm writing an application that has 5 threads that get some information from web simultaneously and fill 5 different fields in a buffer class.
I need to validate buffer data and store it in a database when all threads finished their job.
How can I do this (get alerted when all threads finished their work) ?
推荐答案
我采取的方法是使用 ExecutorService 来管理线程池。
The approach I take is to use an ExecutorService to manage pools of threads.
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
es.execute(new Runnable() { /* your task */ });
es.shutdown();
boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES);
// all tasks have finished or the time has been reached.
这篇关于等到所有线程完成他们在java中的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文