【问题标题】:What if you pass a no-arg in the Thread constructor and don't extend the Thread class?如果您在 Thread 构造函数中传递一个无参数并且不扩展 Thread 类怎么办?
【发布时间】:2018-04-05 18:34:17
【问题描述】:

如果我这样做,后台会发生什么:

class TestThread {
     public static void main(String[] args) {
         Thread t = new Thread();
         t.start();

         System.out.println(t.getName());
     }
}

我知道要创建一个新线程,您必须通过扩展Thread 类或实现Runnable 接口来覆盖run() 方法。

如果我们实现Runnable 接口,我们必须提供目标运行方法,其中提供了必须并发运行的代码。

另外,如果我们不重写 run() 方法并且不扩展 Thread 或实现 Runnablemain() 线程将执行。

我想知道当我执行上述代码时,后台究竟会发生什么?主要有像其他Threads 一样的run() 方法吗?这会在main 线程之外创建一个新的Thread 吗?

【问题讨论】:

    标签: java multithreading java-threads


    【解决方案1】:
    /**
     * If this thread was constructed using a separate
     * Runnable run object, then that
     * Runnable object's run method is called;
     * otherwise, this method does nothing and returns.
     * 
     * Subclasses of Thread should override this method.
     */
    public void run() {
        if (target != null) {
            target.run();
        }
    }
    

    由于您尚未设置Runnable 目标,因此不会发生任何事情。

    main 有没有像其他Threads 一样的run() 方法?

    低级 API 可用于此目的。他们不一定需要创建Thread 实例来运行线程。这是一个很好的讨论:How main thread created by Java?

    【讨论】:

    • 你在哪里找到 run() 方法的这个定义?
    • @SalilJoshi,在 JavaDocs 中
    【解决方案2】:

    新线程被创建、启动、执行空*方法并终止。

    *) 不是真的为空:

    public void run() {
        if (target != null) {
            target.run();
        }
    }
    

    【讨论】:

    • 谢谢,它是在主线程之外创建的。 main 中也有 run() 方法吗?
    • 你在哪里找到 run() 方法的这个定义?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2017-07-30
    相关资源
    最近更新 更多