背景
在執行單元測試的時候,發現同一線程運行多次後,就會報一個線程的錯誤:
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