繁体   English   中英

通过扩展 Thread 类的线程行为

[英]Behavior of thread by extending Thread class

我有以下class‍

public class Thread1 extends Thread {
  @Override
  public void run() {
    System.out.println("I am the first thread");
  }

 public static void main(String args[]) {
    Thread1 t = new Thread1();
    t.start();  
    }
}

如果我运行上面的程序,它将在新线程中打印

"I am the first thread"

现在在 main 中,如果我尝试启动同一个线程两次,它将抛出java.lang.IllegalThreadStateException

现在我将通过覆盖start()方法重写 Thread1 类,如下所示

public class Thread1 extends Thread {
  @Override
  public void run() {
    System.out.println("I am the first thread");
  }

  @Override
  public void start() {
    System.out.println("I am the Start");
  }

  public static void main(String args[]) {
    Thread1 t = new Thread1();
    t.start();  
    t.start();  
    }
  }

现在,如果我调用start()方法两次,输出将是:

  I am in start
  I am in start

上面的程序抛出任何异常。 谁能解释我这种行为。 为什么它不启动新线程。 看似简单,却看不懂。

@Override一个方法时,您正在创建的新方法将被调用而不是之前的方法。

Thread类中, start()是一种执行某些操作并启动 Thread 的方法。

在你的新类Thread1start()是一个只打印一行Thread1做其他事情的方法


您的理解是正确的 - 调用super.start()是调用超类的start()版本,它允许线程实际开始运行。

但请注意,当您尝试运行它两次时仍然会遇到该异常。 这就是Thread的设计方式。

来自问题评论中的链接:

多次启动一个线程是不合法的。 特别是,线程一旦完成执行就可能不会重新启动。

暂无
暂无

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

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