I got a fixed number of threads. I want each thread to run three Runnables, one after another. Here’s some pseudocode to explain:
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
// Set the first tasks.
threads[i] = new Thread(new FirstRunnable());
threads[i].start();
}
for (int i = 0; i < threads.length; i++)
threads[i].join(); // wait until the first tasks are done
for (int i = 0; i < threads.length; i++) {
// Set the second task.
threads[i].setRunnable(new SecondRunnable());
threads[i].start();
}
for (int i = 0; i < threads.length; i++)
threads[i].join(); // wait until the second tasks are done
...
Using a ThreadPool sounds way overkill, especially since I’m headed for performance, performance, performance. What’s the best way to implement this in Java?
Whenever you see
new Thread(...).start(), make use of theExecutorsframework. In particular, make use ofExecutors.newFixedThreadPool(...).