Java的。线程执行的顺序

Java的。线程执行的顺序

问题描述:

我尝试从书中运行示例(Paul Hyde,Java Thread Programming)。它说线程的顺序会互换。但我总是得到:10主线打印和10新线程之后。
更有趣的是:如果我将使用tt.run而不是tt.start,那么结果将反之亦然。也许这本书很老的原因,例子是基于JDK 1.2 ???代码如下:

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");
        }
    }
}


JVM决定何时将控制权从主线程转移到第二个线程。由于主线程在启动第二个线程后没有执行太多工作,因此JVM让它在将控制转移到第二个线程之前完成其工作是有道理的。

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.

你使用 tt.run()而不是 tt.start()你没有开始第二个线程。您正在主线程中执行 run()方法。因此,您首先看到新主题输出。

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.