What is the best way to wait for a Java thread to finish, while doing something else? Since I need to do stuff while I wait, I can't use join()
. I was going to just poll on isAlive()
but I have read that that is discouraged (though it seems like it would be perfect for my case). Also, I've seen some indication that isAlive()
could return false before the thread has actually started (https://stackoverflow.com/a/702427/783314). Though that comment might simply be incorrect since it seems to contradict the Java documentation "A thread is alive if it has been started and has not yet died." (https://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#isAlive%28%29)
What I want is basically something like stillRunning() in my below example. Though if there's another, better, reasonably simple alternative that does the same thing, I am open to it.
All I need to do is know when the thread has finished. I don't need to otherwise communicate with it.
public class MyService implements Runnable {
public void run() {
for (int j = 0; j < 5; j++){
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("Hello from a thread!");
}
catch (InterruptedException e){
//don't care
}
}
@RequestMapping(value = "/test")
@ResponseBody
void test(HttpServletResponse response) {
Thread t = (new Thread(new MyService()));
t.start();
while (t.stillRunning()){
System.out.println("Yup, t is still running");
//do some important stuff while waiting
}
System.out.println("Ok, now we know t is done");
}
}