How does this thread join() work as given?

java, multithreading

Solution

`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

Problem

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. "); } } ```

Original source