I know we can execute Runnables in an ExecutorService which will be executed as separate threads. But I recently came across a situation where I need to know the state of a Thread during its executions. For that I created instances of Threads (instead of Runnable) and submitted it to an ExecutorService. However, the Thread state remained in NEW state. Syntactically the program had no errors but I feel I am missing something. Here is the sample program:
public class ThreadStates3 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(getRunnable());
Thread thread2 = new Thread(getRunnable());
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(thread);
service.execute(thread2);
while (true) {
System.out.println("Thread 1: " + thread.getState() + ", Thread 2: " + thread2.getState());
Thread.sleep(1000);
boolean taskComplete = thread.getState() == Thread.State.TERMINATED &&
thread2.getState() == Thread.State.TERMINATED;
if (taskComplete) break;
}
System.out.println("Program complete.");
}
static Runnable getRunnable() {
return () -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
}
}