Interview Questions

What will be the output for the following code?

public class ThreadTest {

        /**
         * @param args
         * @throws InterruptedException
         */

        public static void main(String[] args) throws InterruptedException
        {
                JoinThread j1 = new JoinThread("one");
                JoinThread j2 = new JoinThread("two");
                j1.start();
                j1.join();
                j2.start();
        }
       
}


class JoinThread extends Thread
{
        private String name;

        public JoinThread(String name)
        {
                this.name = name;
        }
       
        public void run()
        {
                for(int i=0;i<3;i++)
                {
                        System.out.println(name);
                }
        }
}

Output:
The above program will output the message "one" 3 times followed by message "two" 3 times.
The join() method makes the main thread to wait for the running thread to die and then execute the remaining lines of code.

one
one
one
two
two
two