I'm a newbie to java and currently working with a training material, where the below code produces the following output:
Run. Run. doIt
How does it print Run. twice? How does the t.join() work?
public class TestTwo extends Thread {
public static void main (String[] a) throws Exception {
TestTwo t = new TestTwo();
t.start();
t.run();
t.join();
t.doIt();
}
public void run() {
System.out.print("Run. ");
}
public void doIt() {
System.out.print("doIt. ");
}
}
t.start() starts the execution of the new thread, which will execute the code in t.run(). But the call to t.start() will return immediately; it won't wait for that thread to finish its execution of run(). After t.start() returns, the main thread runs t.run(). Finally, it'll wait for the t thread to finish, which is what t.join() does. This method will not return immediately, but will instead wait for the thread to finish. (As it happens, that's going to be very fast in this case -- but it could potentially take minutes, hours, or even forever.)
The control flow looks something like this:
Thread A
|
+- t.start() ---> starts Thread B
+- t.run() +- t.run()
| |
+- t.join() waits for B |
| to finish |
| \------> +- Thread B stops
+- t.doIt()
+- Thread A stops
t.run();
is an extraneous call.
When you start the thread with t.start() it is started independently. This prints "run" to the screen.
Then, t.run( runs the thread's run( method which also prints run. These two prints of "run" can be in either order.
Lastly, we call t.join. This waits for the thread to terminate(after its print by design of join, and after the print from run as the run call is before and blocking.
After the join the doIt function is called in a blocking manner.
In a nutshell, the main and t threads both print run and then the main thread waits until the t thread is finished to print doIt.
Although many of the calls are part of t threading acts somewhat independently of instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With