java 一个线程多次执行,Java-Java线程调用可以多次启动吗?

博主探讨了在Java中是否可以合法地在一个线程上调用start方法两次。尽管规范规定线程不能重复启动,但实际运行代码并未抛出预期的IllegalThreadStateException。实验和分析揭示了问题在于两个独立的Thread对象调用,而非同一实例。讨论了可能的后果并提供了解决方法。
摘要由CSDN通过智能技术生成

Folks,

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?

From the spec,

It is never legal to start a thread

more than once. In particular, a

thread may not be restarted once it

has completed execution.

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) 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.

Why ?

Q.2) If at all we did start a new thread on the same instance, what harm it would do ?

Any help would be greatly appreciated !

解决方案

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

new Thread(thread).start();

new Thread(thread).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();

which is fortunately asked by me :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值