【问题标题】:what is the difference between the two structures of creating threads mentioned below [duplicate]下面提到的两种创建线程的结构有什么区别[重复]
【发布时间】:2015-11-10 17:49:37
【问题描述】:

结构 1:

public class Runner {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread(){
            public void run() {
                System.out.println("value :");
            }
        });
        t1.start();
    }
}

结构2:

public class Runner {
    public static void main(String[] args) {
        Thread t1 = new Thread(){ 
            public void run(){
                System.out.println("value :"); 
            }
        };
        t1.start();
    }
}

这两种情况的结果是一样的。

上面提到的两个结构有什么区别?请解释一下。

【问题讨论】:

  • 请使用帮助了解如何在 SO 文章中包含代码。

标签: java multithreading java-threads


【解决方案1】:

您在第一个示例中使用内部类执行线程。所以基本上你在第一个例子中将一个线程的对象传递给另一个线程。

start() 方法总是寻找运行方法。并且 t1.start() 在两个示例中都在那里运行线程。

【讨论】:

    【解决方案2】:

    在第一个示例中,您在构造函数中为 Thread 提供了一个 Thread。它很奇怪,它之所以有效,是因为 Thread 实现了 Runnable,但不鼓励像这样使用它。只需在构造函数中使用 Runnable

    默认情况下,Thread 的run() 方法只运行给构造函数的 Runnable。如果不提供Runnable,也不覆盖Thread的run方法,那么它基本上不会执行任何代码。

    我的 Thread 类的反编译 run 方法如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      相关资源
      最近更新 更多