【发布时间】:2023-03-24 15:48:02
【问题描述】:
当ThreadPoolExecutor 中的所有线程都完成时,如何通知我的主类实例化ThreadPoolExecutor?
ThreadPoolExecutor threadPool = null;
ThreadClass threadclass1;
ThreadClass threadclass2;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(maxPoolSize);
puclic MyClass(){
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);
threadClass1 = new ThreadClass;
threadClass2 = new ThreadClass;
threadPool.execute(threadClass1);
threadPool.execute(threadClass2);
//Now I would like to do something until the threadPool is done working
//The threads fill a ConcurrentLinkedQueueand I would like to poll
//the queue as it gets filled by the threads and output
//it to XML via JAX-RS
}
编辑 1
当我的线程从某个地方获取数据并将这些信息填充到 ConcurrentLinkedQueue 中时,我基本上想在 MyClass 中执行一些操作以使用结果更新 XML 输出。当所有线程都终止时,我想向实例化 MyClass 的 JAX-RS Web 服务返回 true,以便 Web 服务知道所有数据都已获取,它现在可以显示最终的 XML 文件
编辑 2
我将Queue 传递给线程,以便它们可以将项目添加到队列中。当一个driver 完成向articleQueue 添加项目时,我想在我的主类中执行一项操作,从Queue 轮询实体并将其交给response 对象以某种方式显示它。
当我将队列传递给线程时,它们是使用同一个对象还是使用对象的“副本”,以便线程内的更改不会影响主对象?那不是我想要的行为。当我检查Driver 中articleQueue 的大小时,它是18,DriverController 中articleQueue 的大小是0。
当一个线程向队列中添加了一些东西而不是我的 while 循环时,有没有更好的方法来做出反应?如何修改我的代码以访问不同类中的相同对象?
驱动控制器
public class DriverController {
Queue<Article> articleQueue;
ThreadPoolExecutor threadPool = null;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
maxPoolSize);
public DriverController(Response response) {
articleQueue = new ConcurrentLinkedQueue<Article>();
threadPool = new ThreadPoolExecutor();
Driver driver = new Driver(this.articleQueue);
threadPool.execute(driver);
// More drivers would be executed here which add to the queue
while (threadPool.getActiveCount() > 0) {
// this.articleQueue.size() gives back 0 here ... why?
if(articleQueue.size()>0){
response.addArticle(articleQueue.poll());
}
}
}
}
驱动程序
public class Driver implements Runnable{
private Queue<Article> articleQueue;
public DriverAlliedElectronics(Queue articleQueue) {
this.articleQueue = articleQueue;
}
public boolean getData() {
// Here would be the code where the article is created ...
this.articleQueue.offer(article);
return true;
}
public void run() {
this.getData();
// this.articleQueue.size() gives back 18 here ...
}
}
【问题讨论】:
-
我不认为你想等待 threads 完成,你想等待 tasks 完成。这看起来对吗?你已经得到了一些关于等待线程的答案,这可能不是你真正想要的。
-
让我的线程从某处获取数据并将此信息填充到 ConcurrentLinkedQueue 我基本上想在
MyClass中执行一些操作以使用结果更新 XML 输出。当所有线程终止时,我想将true返回到实例化MyClass的 JAX-RS Web 服务,这样 Web 服务就知道所有数据都已获取,它现在可以显示最终的 XML 文件。
标签: java multithreading threadpool