Java Reference
In-Depth Information
■
the
TimeUnit
enum in the
java.util.concurrent
package represents a measurement of time in various units
such as milliseconds, seconds, minutes, hours, days, etc. It has some convenience methods. One of them is the
sleep()
method. the
Thread.sleep()
method accepts time in milliseconds. If you want a thread to sleep for five seconds, you
need to call this method as
Thread.sleep(5000)
by converting the seconds into milliseconds. You can use the
sleep()
method of
TimeUnit
instead to avoid the time duration conversion, like so:
Tip
TimeUnit.SECONDS.sleep(5); // Same as Thread.sleep(5000);
I will Join You in Heaven
I can rephrase this section heading as “I will wait until you die.” That's right. A thread can wait for another thread to
die (or terminate). Suppose there are two threads,
t1
and
t2
. If the thread
t1
executes
t2.join()
, thread
t1
starts
waiting until thread
t2
is terminated. In other words, the call
t2.join()
blocks until
t2
terminates. Using the
join()
method in a program is useful if one of the threads cannot proceed until another thread has finished executing.
Listing 6-12 has an example where you want to print a message on the standard output when the program has
finished executing. The message to print is “We are done.”
Listing 6-12.
An Incorrect Way of Waiting for a Thread to Terminate
// JoinWrong.java
package com.jdojo.threads;
public class JoinWrong {
public static void main(String[] args) {
Thread t1 = new Thread(JoinWrong::print);
t1.start();
System.out.println("We are done.");
}
public static void print() {
for (int i = 1; i <= 5; i++) {
try {
System.out.println("Counter: " + i);
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
We are done.
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5