Java Reference
In-Depth Information
In the
main()
method, a thread is created and started. The thread prints integers from 1 to 5. It sleeps for one
second after printing an integer. In the end, the
main()
method prints a message. It seems that this program should
print the numbers from 1 to 5, followed by your last message. However, if you look at the output, it is in the reverse
order. What is wrong with this program?
The JVM starts a new thread called
main
that is responsible for executing the
main()
method of the class that you
run. In your case, the
main()
method of the
JoinWrong
class is executed by the
main
thread. This thread will execute
the following statements:
Thread t1 = new Thread(JoinWrong::print);
t1.start();
System.out.println("We are done.");
When the
t1.start()
method call returns, you have one more thread running in your program (
thread t1
) in
addition to the
main
thread. The
t1
thread is responsible for printing the integers from 1 to 5, whereas the
main
thread
is responsible for printing the message “We are done.” Since there are two threads responsible for two different tasks, it
is not guaranteed which task will finish first. What is the solution? You must make your
main
thread wait on the thread
t1
to terminate. This can be achieved by calling the
t1.join()
method inside the
main()
method.
Listing 6-13 lists the correct version of Listing 6-12 by using the
t1.join()
method call, before printing the final
message. When the
main
thread executes the
join()
method call, it waits until the
t1
thread is terminated. The
join()
method of the
Thread
class throws a
java.lang.InterruptedException
, and your code should be ready to handle it.
Listing 6-13.
A Correct Way of Waiting for a Thread to Terminate
// JoinRight.java
package com.jdojo.threads;
public class JoinRight {
public static void main(String[] args) {
Thread t1 = new Thread(JoinRight::print);
t1.start();
try {
t1.join(); // "main" thread waits until t1 is terminated
}
catch (InterruptedException e) {
e.printStackTrace();
}
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();
}
}
}
}