Java-Java线程调用可以多次启动吗? [英] Java - Can java thread invoke start more than once?

查看:230
本文介绍了Java-Java线程调用可以多次启动吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们

我知道这里曾有人问过这个问题,尽管是间接的.但这并没有回答我的疑问.
问题:在同一线程上两次调用start方法?

I know this question has been asked before here, though indirectly. But it didn't answer my doubt.
Question : Is it legal to call the start method twice on the same Thread?

规范

启动线程永远是不合法的 不止一次.特别是 线程可能无法重新启动 已经完成执行.

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

我同意.但是我的代码没有抛出 IllegalThreadStateException 可能会在执行以下程序时抛出该错误.

I agree. But my code doesn't throw a IllegalThreadStateException which it is expected to throw on execution of following program.

   public class Tester extends Thread {
        public void run() {
            System.out.print("run");
        }
        public static void main(String[] args) {
            Tester thread = new Tester();
            new Thread(thread).start();
            new Thread(thread).start();
        }
    }    

Q.1)我在Eclipse中运行了以上代码.在这里,由于我试图在同一实例上启动新线程,因此预计会抛出IllegalThreadStateException.但事实并非如此.

Q.1) I ran the above code in Eclipse. Here, since I am trying to start a new thread on the same instance, a IllegalThreadStateException is expected to be thrown. But it doesn't.

为什么?

Q.2)如果我们确实确实在同一实例上启动了一个新线程,那会带来什么危害?

任何帮助将不胜感激!

推荐答案

首先,您要调用两个不同的线程对象,即:

Firstly, you are invoking on two different thread objects ie:

 new Thread(thread).start();
 new Thread(thread).start();

您正在两个不同的实例上调用start方法.出于这个原因,您没有得到例外.

you are calling start method on two different instances. for which reason you are not getting the exception.

尝试以下操作以获取异常

try with following to get the exception

thread.start();
thread.start();

第二个问题.您可以在此处获得答案:

For your second question. you can get the answer here : Why can't we call the start method twice on a same instance of the Thread object?

我很幸运地问到了:)

这篇关于Java-Java线程调用可以多次启动吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆