gpt4 book ai didi

java - 在单独的线程中将对象返回到池

转载 作者:行者123 更新时间:2023-11-29 09:06:04 25 4
gpt4 key购买 nike

有一个循环轮询从 GenericObjectPool 借用对象。池本身的大小为 1。代码如下 -

final CompletionService completionService = new ExecutorCompletionService(getExecutorServices());               
int counter = 0;

for (Iterator iter = AList.iterator(); iter.hasNext();) {

borrowed = this.getPool().borrowObject();

if (borrowed == null) {
throw new Exception("not set");
} else {
completionService.submit(borrowed,borrowed);
counter ++;
}
}

由于池的大小为 1,在第一次借用后,它会耗尽并阻塞。要将对象返回到池中,我想运行一个单独的线程,如下所示 -

new Runnable() {

public void run() {
for (int i = 0; i < counter; i++) {

borrowed = completionService.take().get();
status = borrowed.getStatus();

getPool().returnObject(borrowed);
counter --;

if (status = 1) {
getExecutorServices().shutdownNow();
return;
}
}
}

};

这是对 CompletionService 的阻塞调用,用于在每个线程完成时执行操作并释放它以使其可供借用。

但是这种设计也有缺点,比如无法从Runnable中读取parent的counter。

最佳答案

计数器不是线程安全的。使用 AtomicInteger 并使其可用于可运行代码块和第一个代码块。

关于java - 在单独的线程中将对象返回到池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15002329/

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