在面试时候经常被问到多线程的相关问题:
今天在测试的时候发现下面的代码会抛出异常: 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(),也就是说单一线程不能重复启动.
时间: 2024-10-16 09:47:38