有什么方法可以并行运行固定的最大数量的线程,并在其中一个线程完成后立即重用 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/