Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

multithreading - 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");
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...