0

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");
    }
}
Stephen
  • 8,508
  • 12
  • 56
  • 96
  • `while (t.isAlive()) { /* do other stuff */ }`. – Andy Turner Mar 23 '18 at 22:00
  • Why not use a callback and just simply do stuff until the callback notifies you that the thread is done? – Hovercraft Full Of Eels Mar 23 '18 at 22:02
  • Alternately, use a thread pool or just launch more threads, and let the OS scheduler deal with running threads and removing threads that have finished. – markspace Mar 23 '18 at 22:02
  • In some way `Future` and particularly `CompletableFuture` have been designed to support that. Yet instead of threads you are supposed to use executors and tasks in that case. – yegodm Mar 23 '18 at 22:03
  • @AndyTurner what about the other person's comment that I linked to "Note that isAlive returns false if the thread hasn't started executing yet (even if your own thread has already called start on it)"? If that's true it could complicate matters. – Stephen Mar 23 '18 at 22:04
  • @Stephen check the duplicate question. It describes how to handle that case. – Andy Turner Mar 23 '18 at 22:06
  • @AndyTurner I read through the duplicate and I don't see anything explicitly addressing the idea that it could return false if the thread hasn't started executing. Though I do see lots of assertions that it starts being True as soon as it has started, so maybe that's good enough for me. – Stephen Mar 23 '18 at 22:11
  • @HovercraftFullOfEels would you mind posting some example code? I'm new to Java and it would help a lot. – Stephen Mar 23 '18 at 22:12
  • @AndyTurner in any case, which answer are you talking about which describes how to handle the case of isAlive() returning false at the beginning? I read through the whole Q&A but I don't see it. – Stephen Mar 23 '18 at 22:32
  • @Stephen https://stackoverflow.com/a/46367071/3788176 – Andy Turner Mar 23 '18 at 22:41
  • @AndyTurner Oh, I thought you meant that it had code to deal with the case where it could return false before it starts returning true. Though maybe that's just a red herring. – Stephen Mar 23 '18 at 23:06
  • @HovercraftFullOfEels I thought more about how to implement a callback, but the issue is that it's not sufficient for the thread I create to be able to call a different method when it is done. The method which *creates* the thread needs to be able to watch it and see when it is done. But maybe I don't understand what you mean by callback. – Stephen Mar 24 '18 at 00:01

0 Answers0