Learn Java Programming - Thread Join Method and Thread States

preview_player
Показать описание
In this tutorial I will demonstrate how to use the join() method. When the join() method is invoked on a child thread, the main thread is placed into one of the following states: WAITING or TIMED_WAITING. When the main thread is in the state of WAITING, it will not execute any more statements until the child thread has terminated. When the main thread is in the state of TIMED_ WAITING, it will not execute any move statements until the child thread has terminated or a certain number of milliseconds have passed. There are three overloaded versions of the join() method:
void join() causes the main thread state to change to WAITING
void join(long milliseconds) causes the main thread state to change to TIMED_WAITING for a certain number of milliseconds.
void join(long milliseconds, int nanoseconds) causes the main thread state to change to TIMED_WAITING for a certain number of milliseconds plus nanoseconds - now that is some precision!!!

Because of the way the join() method changes the behavior of thread states, it is perfect opportunity to demonstrate every thread states except BLOCKED.

NEW - A thread has been declared, but has not yet started is in this state.
RUNNABLE - In this state a thread is executing in the JVM.
BLOCKED - In this state a thread is blocked waiting for a monitor lock or intrinsic lock. I'll explain in later down the road.
WAITING - A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED WAITING - A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED - A thread that has exited is in this state.
Рекомендации по теме
Комментарии
Автор

Hi Daniel Ross..!
Your tutorials are very nice. Thank you for your works..
Now in this tutorial I have a doubt..

The snippet is as follows..
constructor, before start(), state = " + this.getState());
start();
constructor, after start(), state = " + this.getState());

But the output is as follows..
MyCalculations constructor, before start(), state = NEW
MyCalculations constructor, after start(), state = RUNNABLE
6223372036854775905 is NOT Prime ... first divisible by 3
Inside MyCalculations run(), Main thread state = WAITING

Why the output should not be like this..?
MyCalculations constructor, before start(), state = NEW
6223372036854775905 is NOT Prime ... first divisible by 3
Inside MyCalculations run(), Main thread state = WAITING
MyCalculations constructor, after start(), state = RUNNABLE

nelsonfernando
welcome to shbcf.ru