gpt4 book ai didi

java - 重用 Runnable 对象

转载 作者:行者123 更新时间:2023-11-30 08:53:04 26 4
gpt4 key购买 nike

有什么方法可以并行运行固定的最大数量的线程,并在其中一个线程完成后立即重用 Runnable 对象?因此,给定 Runnable obj 的 N 组运行参数并且只有 M 个 Runnable 对象(M < N)是否有一种方法可以确保一旦使用 Runnable 对象的线程之一完成,我就使用相同的线程启动一个新线程Runnable obj(因此一次最多运行 M 个线程)?

最佳答案

您可以像这样实现生产者-消费者模式:

    int n = 10;
Executor executor = Executors.newFixedThreadPool(n);
final BlockingQueue<Object> tasks = new ArrayBlockingQueue(1024);
for (int i = 0; i < n; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Object task = tasks.take();
// process task
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
tasks.put(new Object());

关于java - 重用 Runnable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29924120/

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