10

when does a thread reach the terminated status? Does it get terminated when the end of the run() method is reached?

So what is the right way to check if a thread is terminated? Because following condition seems to be true always for me

if(!(thread.getState()).equals("TERMINATED")){}

Any ideas?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

2 Answers2

20

First: Thread.getState() returns a Thread.State, which will never be equal to a String, so you'd need to write that code like this:

if(thread.getState()!=Thread.State.TERMINATED){ }

And yes: when the run() method ends (either normally or because it throws an exception), then a Thread will go to the TERMINATED state.

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 5
    `and yes: when the run() method ends (either normally or because it throws an exception), then a Thread will go to the TERMINATED state.` That's not true actually, w/ abnormal execute like exception it calls the `UncaughtExceptionHandler` and it's free to do whatever it pleases. (incl stuff like `Thread.currentThread().run()`), the thread is in terminate state After exit() method which can block (infinitely) on the `ThreadGroup` sync. – bestsss May 06 '11 at 13:23
  • 1
    @bestsss: and there I hoped no one noticed that little loophole ;-) Yes, you're right of course. – Joachim Sauer May 06 '11 at 13:30
  • Doesnt' work for me, even returns TERMINATED although thread is still playin sounds. – Simon Apr 02 '15 at 09:17
  • @SimonMeier: that sounds like (no pun intended) your thread is actually finished but whatever library you use to play sounds continues playing after the call returned. I'm not an expert on playing sound in Java, but I know that this is pretty common (i.e. your method call just schedules some sound to play and returns before it's actually done playing). – Joachim Sauer Apr 02 '15 at 13:25
  • Ok... But even if there is some Thread.sleep() in that thread? I'm playing shorts sounds in a sequence by setting a sleep of about half a second, which means in total the thread should be alive about 4 seconds, while it is repeatingly calling the Android MediaPlayer to play a sound... – Simon Apr 03 '15 at 07:21
15

test the method thread.isAlive()

... or optionally, join until it finishes with thread.join()

Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56
  • 1
    Apparently .isAlive() has some timing issues: http://stackoverflow.com/questions/3140731/isalive-method-of-java-thread-is-not-working-properly – Simon Apr 02 '15 at 09:14
  • @simon I think the conclusions made there are misleading. It seems clear that the thread state is set asynchronously from the main thread, so testing it immediately after starting the thread can't be expected to work. In fact, I would expect that the result of using `getState()` wouldn't be any different. – orodbhen Jul 26 '17 at 11:16