【问题标题】:What is the flow of control while creating a new thread in Java?在 Java 中创建新线程时的控制流程是什么?
【发布时间】:2018-01-10 23:06:06
【问题描述】:

我正在阅读 Java 中的线程,并通过实现 Runnable 接口并使用 start() 和 run() 函数来创建一个新线程。

我的代码如下:

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类的构造函数。

我读到的是

新线程创建后,它不会开始运行,直到你 调用它的 start() 方法,该方法在 Thread 中声明。在本质上, start( ) 执行对 run( ) 的调用

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

以下是输出:

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,所以它的run()被立即执行。
  • 但是根据输出结果不对?
  • 好的,“立即”是错误的词。一旦轮到新启动的线程运行,打印就会发生,这可能是在从构造函数返回之前或之后。
  • 好的,知道了。谢谢你:)
  • 从线程可以看到的对象的构造函数中启动线程是错误的。 stackoverflow.com/a/5623327/801894

标签: java multithreading runnable


【解决方案1】:

核心概念是,一旦您在子线程上调用start两个线程就会并行运行。

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

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

【讨论】:

  • 所以在并行运行时我无法控制哪个线程先运行?
  • @KaustubhSrivastava - 正确!每个线程都会按预期按自己的顺序做自己的事情,但它们都是同时做的。但是,因为它们都共享同一个控制台,所以它们的输出是交错的。
猜你喜欢
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多