在面试时候常常被问到多线程的相关问题: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(),也就是说单一线程不能重复启动.测试