John February 2016

What is the proper way to start worker threads and then join them?

One of Java's tutorials gives this example on threads. The code snippet below comes from https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html. Here is the part I am asking about (with some minor edits):

Thread t = new Thread(new MessageLoop());
t.start();

while (t.isAlive()) {
    t.join();
}

The main question is this: what happens when t.isAlive() returns false before the thread actually starts? From some tests I ran:

Thread t = new Thread(new Whatever());
t.start();
System.out.println(t.isAlive()+" "+t.getState());

it's possible that t.getState() is NEW and t.isAlive() is false. The above while loop would have never joined my worker thread because isAlive would have returned false (even though the worker thread didn't even start). Is there a better way to join worker threads other than what is shown in the first block of code? Should I be checking the state along with whether it's alive? Maybe something like:

while(t.isAlive() || t.getState()==Thread.State.NEW){ ... }

Answers


Douglas February 2016

Effective Java recommends never using Thread directly and instead using the Executor Framework defined in the java.util.concurrent package. In this framework, you would start off by getting an ExecutorService from one of the static factory methods in Executors, replace both new Thread and t.start() with a call to submit(), and then either coordinate between threads with a CountDownLatch or other provided synchronizer class or (as in your simple case) call get() on the Future that submit() returns.

Note that an ExecutorService, once created, will run forever and potentially keep your program from terminating if you neglect to call shutdown() on it. They are designed to be reused, submitting many different tasks to a single one (which may internally split them up among many different threads), and will continue running until you tell them that no more reuse will happen.

Post Status

Asked in February 2016
Viewed 3,263 times
Voted 5
Answered 1 times

Search




Leave an answer