您的位置:首页 > 编程语言 > Java开发

Java中多线程重复启动

2015-09-03 20:17 344 查看
在面试时候经常被问到多线程的相关问题:

今天在测试的时候发现下面的代码会抛出异常: 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(),也就是说单一线程不能重复启动.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: