Can some one please explain the below Code

public class TestThread implements Runnable {

    public static void main(String[] args) {
        Thread thread = new Thread(new TestThread());
        thread.start();
        System.out.println("1");
        thread.run();
        System.out.println("2");

    }

    @Override
    public void run() {
        System.out.println("3");
    }
}

The output results in 1 3 3 2.Can some one please explain.

Thanks in Advance

1 Answers

1
oscarandjo On Best Solutions

When you call the thread.start() method, then the code inside the run() method will be executed on a new thread (since class TestThread implements Runnable).

When you call thread.run(), this is calling the run() method from within the Main thread, not the one you started previously. This is essentially not using any threaded functionality.

Once this run() function has finished from the Main thread, it exits this function and reaches the println("2") line.

It might seem intuitive that since you called thread.start() before println("1") that it should print "3 1 3 2", however, due to the complexities of multithreading there is no guarantee of any ordering in the way this has been implemented. It could print "1 3 3 2" or "3 1 3 2" depending on many factors.

An experiment you could try is to get the print statements to include the names of the threads they're called from.

public class TestThread implements Runnable {

    public static void main(String[] args) {
        Thread thread = new Thread(new TestThread(), "newThread");
        thread.start();
        System.out.println(Thread.currentThread().getName() + ": 1");
        thread.run();
        System.out.println(Thread.currentThread().getName() + ": 2");
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": 3");
    }
}

For me, this outputs:

main: 1
main: 3
newThread: 3
main: 2