I am learning how to use thread pools in Java using ExecutorService
, here is an example I am working on:
public class Example {
static class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.command;
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
// while (!executor.isTerminated()) {
// }
System.out.println("Finished all threads");
}
}
I have two questions:
How should I wait for the termination of an
ExecutorService
, should I useawaitTermination()
orisTerminated()
(it has been suggested that the latter is a wrong way to do it)?Are the
Runnable
s correctly added to the executor or should I usesubmit()
together with aFuture<T>
callback?
It probably depends on the context, so would you please explain (for both questions) when should I use each of the solutions mentioned.