在面試時候經常被問到多線程的相關問題:
今天在測試的時候發現下面的代碼會拋出異常: 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(),也就是說單一線程不能重復啟動.
