Leo Mish
Leo Mish

Reputation: 89

Java. The order of threads execution

I try to run the example from a book(Paul Hyde, Java Thread Programming). It says that the order of threads will interchange. But I always get : 10 "Main thread" prints and 10 "New thread" ones afterwards. What is more interesting : if I will use tt.run instead of tt.start then result will be vice versa. Maybe the reason that the book is quite old and examples are base on JDK 1.2??? Code is below:

public class TwoThread extends Thread
{
    public void run()
    {
        for (int i = 0; i < 10; i++)
        {
            System.out.println("New thread");
        }
    }

    public static void main(String[] args)
    {
        TwoThread tt = new TwoThread();
        tt.start();

        for (int i = 0; i < 10; i++)
        {
            System.out.println("Main thread");
        }
    }
}

Upvotes: 5

Views: 856

Answers (2)

harsh
harsh

Reputation: 7692

if I will use tt.run instead of tt.start then result will be vice versa.

tt.run runs in main thread only whereas tt.start spawns another thread. Hence the result is expected.

On seeing consistency:

for smaller and quick activities you may see consistent result occasioanly but that doesn't mean the order of print you are seeing is guaranteed. Increase loop iteration to higher number and see the order of print (say printing upto 10000 times)

Upvotes: 1

Eran
Eran

Reputation: 393841

The JVM decides when to transfer control from the main thread to the second thread. Since the main thread doesn't perform much work after starting the second thread, it makes sense the JVM lets it complete its work before trasfering control to the second thread.

When you use tt.run() instead of tt.start() you are not starting a second thread. You are executing the run() method in the main thread. Therefore you see the "New thread" outputs first.

Upvotes: 7

Related Questions