Java Reference
In-Depth Information
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
We are done.
The join() method of the Thread class is overloaded. Its other two versions accept a timeout argument. If you
use the join() method with a timeout, the caller thread will wait until the thread on which it is called is terminated or
the timeout has elapsed. If you replace the t1.join() statement in the JoinRight class with t1.join(1000) , you will
find that the output is not in the same order because the main thread will wait only for a second for the t1 thread to
terminate before it prints the final message.
Can a thread join multiple threads? The answer is yes. A thread can join multiple threads like so:
t1.join(); // Join t1
t2.join(); // Join t2
t3.join(); // Join t3
You should call the join() method of a thread after it has been started. If you call the join() method on a thread
that has not been started, it returns immediately. Similarly, if you invoke the join() method on a thread that is
already terminated, it returns immediately.
Can a thread join itself? The answer is yes and no. Technically, it is allowed for a thread to join itself. However,
a thread should not join itself in most circumstances. In such a case, a thread waits to terminate itself. In other words,
the thread waits forever.
// "Bad" call (not if you know what you are doing) to join. It waits forever
// until another thread interrupts it.
Thread.currentThread().join();
If you write the statement, make sure that your program interrupts the waiting thread using some other threads.
In such a case, the waiting thread will return from the join() method call by throwing an InterruptedException .
Be Considerate to Others and Yield
A thread may voluntarily give up the CPU by calling the static yield() method of the Thread class. The call to the
yield() method is a hint to the scheduler that it may pause the running thread and give the CPU to other threads.
A thread may want to call this method only if it executes in a long loop without waiting or blocking. If a thread
frequently waits or blocks, the yield() method call is not very useful because this thread does not monopolize the
CPU and other threads will get the CPU time when this thread is blocked or waiting. It is advisable not to depend on
the yield() method because it is just a hint to the scheduler. It is not guaranteed to give a consistent result across
different platforms. A thread that calls the yield() method continues to hold the monitor locks. Note that there is no
guarantee as to when the thread that yields will get the CPU time again. You may use it like so:
// The run() method of a thread class
public void run() {
while(true) {
// do some processing here...
Thread.yield(); // Let's yield to other threads
}
}
 
Search WWH ::




Custom Search