繁体   English   中英

通过扩展线程类创建线程时的混乱

[英]confusion while creating a thread by extending thread class

我们知道我们可以通过创建一个扩展线程的新类来创建一个新线程,然后创建该线程的一个实例..在阅读这个主题时,我在我的书中看到了一个例子,如下所示。

 class NewThread extends Thread{
    NewThread(){
        super("demo thread");
        System.out.println("child thread:"+this);
        start();
    }
    public void run(){
        try{
            for(int i=5;i>0;i--){
                System.out.println("child thread"+i);
                Thread.sleep(500);
            }
         } catch(InterruptedException e){
             System.out.println("child interrupted");
         }
         System.out.println("exiting child thread");
      }
  }

在这个例子中,除了我们没有使用任何实例(线程)来调用 start() 的构造函数部分之外,我能够理解所有这些东西。所以我的问题是如何在没有任何线程的情况下调用 start() 方法。

您正在从 NewThread 类扩展的类 Thread 继承 start() 方法。 所以你可以像任何其他方法一样调用它。

run() 方法也是如此,该方法可以使用 @Override 注释以使继承的概念更清晰。

@Override
public void run() {
        try{
            for(int i = 5; i > 0; i--) {
                System.out.println("child thread" + i);
                Thread.sleep(500);
            }
        } catch(InterruptedException e) {
           System.out.println("child interrupted");
        }
        System.out.println("exiting child thread");
    }

它是有效的,因为方法start()继承自Thread类,因此您可以像调用任何其他类方法一样调用它。

这个 start() 方法是在线程实例上调用的,线程实例刚刚在这个构造函数中创建。

下面的代码负责调用start()方法在你NewThread的情况下NewThread构造函数,它调用start()方法Thread类,它调用run()方法。

 NewThread(){
    super("demo thread");
    System.out.println("child thread:"+this);
    start();
}

流动:

NewThread() -> start() -> Thread start() -> native start0() ->  run()

有关Threadstart()方法的内部结构,请参阅此 SE 问题:

Thread start() 和 Runnable run() 有什么区别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM