【问题标题】:Why is this thread affecting the main thread?为什么这个线程会影响主线程?
【发布时间】:2014-05-26 02:39:14
【问题描述】:

我一定是错过了什么:

public class Test {
    public static void main(String[] args) {
        (new Thread(new Action())).run();
        System.out.println("Blah");
    }
}

class Action implements Runnable {
    public void run() {
        while (true) {

        }
    }
}

我创建了一个应该运行循环的线程。

在我的主线程中,我打印“Blah”。

但是,它永远不会被打印出来。为什么不?如果我创建一个单独的线程,它应该不会影响我的主执行线程,对吧?

这台机器有四个核心。

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    调用start() 而不是run() 来启动一个线程。

    简单地调用run()意味着在同一个main线程中进行无限循环的方法调用,这将阻塞在main线程中编写的下一条语句。

    看看Java Tutorial on Defining and Starting a Thread


    我应该是(new Thread(new Action())).start(); 来启动一个线程,但它仍然会创建一个无限循环并且新启动的线程永远不会停止。

    尝试使用Thread.currentThread().getName()再次确认,如下所示:

    public void run() {
        System.out.println(Thread.currentThread().getName()); // output "main"
    }
    

    线程生命周期及其方法的图示

    【讨论】:

      【解决方案2】:

      因为不是调用start(),而是直接调用线程run()的实现方法,所以没有启动线程,只是执行代码。

      run()是线程内部结构调用来执行任务的方法,因为它只是一个没有附加任何东西的普通方法。

      【讨论】:

        猜你喜欢
        • 2020-08-31
        • 1970-01-01
        • 2017-02-28
        • 1970-01-01
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        相关资源
        最近更新 更多