Java中多线程重复启动
2015-09-03 20:17
344 查看
在面试时候经常被问到多线程的相关问题:
今天在测试的时候发现下面的代码会抛出异常: java.lang.IllegalThreadStateException
改成下面这样就可以顺利运行了
总结:线程不能重复调用start(),也就是说单一线程不能重复启动.
今天在测试的时候发现下面的代码会抛出异常: 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(),也就是说单一线程不能重复启动.
相关文章推荐
- 20150902 Java学习笔记-构造方法,关键字,封装性
- 控制程序流程
- Java中@Override的作用
- java下io文件切割合并功能
- 实现抽取java中的注释的代码
- 一切都是对象
- Spring Data JPA查询关键字
- Java的类加载
- 关于Java中的反射的一个简单使用
- java注释
- Java中父类强制转换为子类的可能
- java 重载与重写
- java中IO递归写入
- 这几天学习java里面的子类父类继承接口重载重写。学的好吃力。我得想办法赶紧理解理解!
- Java 编写注释规范模板
- java自定义异常
- 使用Java正则表达式匹配IP
- Java内部类的使用小结
- Java 线程的suspend()和stop()不安全的原因
- Spring BeanFactory getBean 源码剖析