简体   繁体   English

通过扩展 Thread 类的线程行为

[英]Behavior of thread by extending Thread class

I have following 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();  
    }
}

If I run the above program it will print in new thread如果我运行上面的程序,它将在新线程中打印

"I am the first thread"

Now in the main if I try to start the same thread twice it will throw java.lang.IllegalThreadStateException现在在 main 中,如果我尝试启动同一个线程两次,它将抛出java.lang.IllegalThreadStateException

Now I will rewrite the Thread1 class as below by overriding the start() method现在我将通过覆盖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();  
    }
  }

Now if I call start() method twice the output will be :现在,如果我调用start()方法两次,输出将是:

  I am in start
  I am in start

The above program is throwing any exception.上面的程序抛出任何异常。 Can anyone explain me this behavior.谁能解释我这种行为。 Why it is not starting the new thread.为什么它不启动新线程。 Seems be to simple but not able understand it.看似简单,却看不懂。

When @Override ing a method, your new method that you are creating is what is going to be called instead of the previous method.@Override一个方法时,您正在创建的新方法将被调用而不是之前的方法。

In class Thread , start() is a method which does some stuff and starts the Thread.Thread类中, start()是一种执行某些操作并启动 Thread 的方法。

In your new class Thread1 , start() is a method which just prints out a line and does nothing else在你的新类Thread1start()是一个只打印一行Thread1做其他事情的方法


Your understanding is correct - that calling super.start() is calling the superclass's version of start() which is allowing the Thread to actually start running.您的理解是正确的 - 调用super.start()是调用超类的start()版本,它允许线程实际开始运行。

Note though, that you are still going to be hitting that exception when trying to run it twice.但请注意,当您尝试运行它两次时仍然会遇到该异常。 This is the way Thread is designed.这就是Thread的设计方式。

From link in comment on question:来自问题评论中的链接:

It is never legal to start a thread more than once.多次启动一个线程是不合法的。 In particular, a thread may not be restarted once it has completed execution.特别是,线程一旦完成执行就可能不会重新启动。

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

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