Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...