一、異常定義
IllegalThreadStateException是Java中一個線程異常。當嘗試在不該啟動的線程上調用start()
方法,或在已經停止的線程上調用resume()
方法時,將拋出IllegalThreadStateException。
二、異常原因
IllegalThreadStateException異常的出現是由於Java線程的狀態不正確而導致的。請參考下面的代碼:
Thread thread = new Thread(); thread.start(); // 狀態1:線程已啟動,但未進入可運行狀態 if(thread.getState() == Thread.State.NEW) { try { thread.start(); } catch (IllegalThreadStateException e) { System.out.println("線程未進入可運行狀態"); } } // 狀態2:線程已運行,但未調用wait()或sleep() if(thread.getState() == Thread.State.RUNNABLE) { try { thread.start(); } catch (IllegalThreadStateException e) { System.out.println("線程已經啟動"); } } // 狀態3:線程已經停止 if(thread.getState() == Thread.State.TERMINATED) { try { thread.resume(); } catch (IllegalThreadStateException e) { System.out.println("線程已經停止"); } }
三、異常解決
避免IllegalThreadStateException的方法有以下幾點:
1、在啟動線程之前,確保線程已經進入可運行狀態。
Thread thread = new Thread(new Runnable() { @Override public void run() { // 線程需要執行的代碼 } }); thread.start();
2、在重複啟動線程前,確保線程已經停止。
Thread thread = new Thread(new Runnable() { @Override public void run() { // 線程需要執行的代碼 } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } thread.start();
3、避免使用suspend()和resume()方法。
下面的代碼演示了為何不使用suspend()和resume()方法,這將導致線程無法停止:
Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("線程啟動"); while (true) { // 死循環 } } }); thread.start(); Thread.sleep(1000); thread.suspend(); Thread.sleep(1000); thread.resume(); // 線程無法停止
四、異常案例
下面的代碼演示了IllegalThreadStateException異常的出現:
Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("線程啟動"); } }); thread.start(); thread.start(); // IllegalThreadStateException異常
五、異常總結
IllegalThreadStateException是Java線程中的一個異常,當線程狀態不正確時會出現該異常。避免出現該異常的方式有:確保線程已經進入可運行狀態、確保線程已經停止以及避免使用suspend()和resume()方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/243951.html