0

Two ways exist to determine whether a thread has finished. First, you can call isAlive() on the thread. This method is defined by Thread, and its general form is shown here:

final boolean isAlive()

The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise. While isAlive() is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join()

isAlive() vs join(). Advantages?

async
  • 1,537
  • 11
  • 28
Upen
  • 1,388
  • 1
  • 22
  • 49

3 Answers3

2

While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( )

I don't understand. Why, according to you, join() is more commonly used than isAlive()? Do you have a proof for that?

They are two different methods defined for the Thread class:

isAlive():

Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

join():

Waits for this thread to die.

One method performs a check, the other one waits for death of thread.

You'll use isAlive(), when you want to perfom a check about the life of a thread, without waiting, and it will return a boolean value about the status of thread.

You'll use join() if you want to wait for the death of thread. The meaning is that you want to wait for the completion of the task assigned to the thread.

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
1

The isAlive() method returns true if the thread upon which it is called is still running.

That is not quite true - public final boolean isAlive()

Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

This means that you may get a false from isAlive if the thread has not yet started while 'join' will wait for it to start and finish before returning.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

If you want to block until Thread is finished, then use join(). Otherwise - you decide.

If your logic does not block waiting for the thread then I think cleaner code look will be achieved with isAlive(). Just look at your code and see what looks nicer.

akostadinov
  • 17,364
  • 6
  • 77
  • 85