java - What is the proper way to start worker threads and then join them? -
one of java's tutorials gives example on threads. code snippet below comes https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html. here part asking (with minor edits):
thread t = new thread(new messageloop()); t.start(); while (t.isalive()) { t.join(); } the main question this: happens when t.isalive() returns false before thread starts? tests ran:
thread t = new thread(new whatever()); t.start(); system.out.println(t.isalive()+" "+t.getstate()); it's possible t.getstate() new , t.isalive() false. above while loop have never joined worker thread because isalive have returned false (even though worker thread didn't start). there better way join worker threads other shown in first block of code? should checking state along whether it's alive? maybe like:
while(t.isalive() || t.getstate()==thread.state.new){ ... }
effective java recommends never using thread directly , instead using executor framework defined in java.util.concurrent package. in framework, start off getting executorservice 1 of static factory methods in executors, replace both new thread , t.start() call submit(), , either coordinate between threads countdownlatch or other provided synchronizer class or (as in simple case) call get() on future submit() returns.
note executorservice, once created, run forever , potentially keep program terminating if neglect call shutdown() on it. designed reused, submitting many different tasks single 1 (which may internally split them among many different threads), , continue running until tell them no more reuse happen.
Comments
Post a Comment