在面試時候常常被問到多線程的相關問題:java
今天在測試的時候發現下面的代碼會拋出異常: java.lang.IllegalThreadStateException面試
public static void main(String[] args)throws Exception{ Test_Thread temp = new Test_Thread(); Test_Thread temp1 = new Test_Thread(); Thread t = new Thread(temp); Thread t1 = new Thread(temp1); for(int i=0;i<50;i++){ if(i%2 == 0){ t.start(); } else { t1.start(); } } }
改爲下面這樣就能夠順利運行了多線程
public static void main(String[] args)throws Exception{ Test_Thread temp = new Test_Thread(); Test_Thread temp1 = new Test_Thread(); // Thread t = new Thread(temp); // Thread t1 = new Thread(temp1); for(int i=0;i<50;i++){ if(i%2 == 0){ new Thread(temp).start(); } else { new Thread(temp1).start(); } } }
總結:線程不能重複調用start(),也就是說單一線程不能重複啓動.測試