gpt4 book ai didi

Java:当线程池中的所有线程都完成时通知主类/不同线程中的相同对象实例

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:51 25 4
gpt4 key购买 nike

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 输出。当所有线程都终止时,我想返回 true 到实例化 MyClass 的 JAX-RS web 服务,以便 web 服务知道所有数据都已被获取,它现在可以显示最终的 XML 文件

编辑2

我正在将一个Queue 传递给线程,这样它们就可以将项目添加到队列中。当一个 driver 完成向 articleQueue 添加项目时,我想在我的主类中执行一个操作,从 Queue 轮询实体并处理它传递给 response 对象以某种方式显示它。

当我将队列传递给线程时,它们是使用同一个对象还是使用对象的“副本”,以便线程内的更改不会影响主对象?那不是我想要的行为。当我检查 DriverarticleQueue 的大小时,它是 18articleQueue 的大小在DriverController0

除了我的 while 循环,当一个线程向队列中添加了一些东西时,有没有更好的 react 方式?我必须如何修改我的代码才能访问不同类中的同一对象?

驱动 Controller

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 ...

}
}

最佳答案

您应该尝试使用以下代码段

//Now I would like to wait until the threadPool is done working
threadPool.shutdown();
while (!threadPool.isTerminated()) {
try {
threadPool.awaitTermination(10, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

关于Java:当线程池中的所有线程都完成时通知主类/不同线程中的相同对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6723307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com