Is there any way that I can run a fixed maximum amount of threads in parallel and REUSE the Runnable object as soon as one of the threads finishes? So, given N sets of running parameters for Runnable obj and only M Runnable objects (M < N) is there a way to make sure that as soon as one of the threads using a Runnable object finishes, I start a new thread using the same Runnable obj (thus a maximum of M threads running at one time) ?
You can implement Producer-Consumer pattern like:
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With