【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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章