背景
在执行单元测试的时候,发现同一线程运行多次后,就会报一个线程的错误:
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