【Bug总结】java.lang.IllegalThreadStateException报错bug的解析

背景

在执行单元测试的时候,发现同一线程运行多次后,就会报一个线程的错误:

  Exception in thread "Main Thread" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:595)
at thread.ThreadTest.main(ThreadTest.java:19)

但是如果仅调用一次该线程的start()方法的时候,就不会报错

问题解析

thread.start()查询源码后发现,在线程开始的时候,会将hasBeenStarted设置成true,在interrupt终止,但却没有将hasBeenStarted设置成false,因此在第二次调用start方法的时候,会抛出IllegalThreadStateException的错误。

 public synchronized void start() {
        checkNotStarted();

        hasBeenStarted = true;

        nativeCreate(this, stackSize, daemon);
    }
 private void checkNotStarted() {
        if (hasBeenStarted) {
            throw new IllegalThreadStateException("Thread already started");
        }
    }
解决方案

1、将extends Thread线程类改成implements Runnable,或者将Thread a = new Thread改为Runnable a = new Runnable;
2、每次new新的线程运行线程,new Thread(robot).start启动多次即可。

参考

1、https://stackoverflow.com/questions/7315941/java-lang-illegalthreadstateexception

2、https://stackoverflow.com/questions/8072933/why-does-an-illegalthreadstateexception-occur-when-thread-start-is-called-again

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值