在 Java 中创建新线程时的控制流是什么?

What is the flow of control while creating a new thread in Java?

我在 java 中阅读了有关线程的内容,并通过实现 Runnable 接口并使用 start() 和 运行() 函数创建了一个新线程。

我的代码如下:

class NewThread implements Runnable
{
    Thread t;

    NewThread()
    {
        t = new Thread(this,"Demo Thread");
        System.out.println("Child Thread: " + t);
        t.start();
    }
    public void run()
    {
        try
        {
        for(int i = 5; i > 0; i--)
        {   
            System.out.println("Child Thread: " + i);
            t.sleep(500);
        }
    }
    catch(InterruptedException e)
    {
        System.out.println("Exception Caught!");
    }
    System.out.println("Exiting child thread!");
    }
}

class Threads
{
public static void main(String args [])
{
    new NewThread();

    try
    {
        for(int i = 5; i > 0; i--)
        {
            System.out.println("Main thread: " + i);
            Thread.sleep(1000);
        }
    }
    catch(InterruptedException e)
    {
        System.out.println("Exception caught!");
    }
    System.out.println("Exiting main thread!");
    }
}

从main函数的第一行开始,调用NewThread的构造函数class。

我读到的是

After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( )

那为什么主线程运行在start()被调用之后,子线程运行()函数却没有呢?

输出如下:

C:\Users\Kaustubh Srivastava\Desktop\Java\Test>java Threads
Child Thread: Thread[Demo Thread,5,main]
Main thread: 5
Child Thread: 5
Child Thread: 4
Main thread: 4
Child Thread: 3
Child Thread: 2
Main thread: 3
Child Thread: 1
Exiting child thread!
Main thread: 2
Main thread: 1
Exiting main thread!

核心概念是,一旦您在子线程上调用了 start两个 线程运行宁 并行.

您在打印输出中看到的是主线程刚好先打印它的第一行。它可以很容易地成为子线程。

本质上这句话很难理解,但是一旦你理解了并行线程运行异步,那么它们做事的顺序几乎是任意交错的。