多线程3
2015-08-06 16:29
246 查看
1、wait和sleep的区别
①wait可以指定时间,也可以不指定时间。sleep必须指定时间,因为sleep可以不需要别人唤醒,可以自己醒过来。
②sleep释放执行权,释放锁。wait释放执行权,不释放锁。
2、停止线程的方式
①通过在run方法中定义标志位的形式,判断标志位的改变,来结束进程
②当线程冻结时,无法判断标志位flag,无法继续执行线程。这时可以用interrupt方法来将线程强制从冻结状态恢复到运行状态来,让线程具备CPU的执行资格。强制动作会发生InterruptedException异常,需要处理。
①wait可以指定时间,也可以不指定时间。sleep必须指定时间,因为sleep可以不需要别人唤醒,可以自己醒过来。
②sleep释放执行权,释放锁。wait释放执行权,不释放锁。
2、停止线程的方式
①通过在run方法中定义标志位的形式,判断标志位的改变,来结束进程
class StopThread implements Runnable { private boolean flag = true; public synchronized void run() { while(flag) { System.out.println(Thread.currentThread().getName()+"......++++"); } } public void setFlag() { flag = false; } } class StopThreadDemo { public static void main(String[] args) { StopThread st = new StopThread(); Thread t1 = new Thread(st); Thread t2 = new Thread(st); t1.start(); t2.setDaemon(true); t2.start(); int num = 1; for(;;) { if(++num==50) { st.setFlag(); break; } System.out.println("main...."+num); } System.out.println("over"); } }通过在循环中判断flag的值来确定是否结束线程。
②当线程冻结时,无法判断标志位flag,无法继续执行线程。这时可以用interrupt方法来将线程强制从冻结状态恢复到运行状态来,让线程具备CPU的执行资格。强制动作会发生InterruptedException异常,需要处理。
class StopThread implements Runnable { private boolean flag = true; public synchronized void run() { while(flag) { try { wait(); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName()+"....."+e); flag = false; } System.out.println(Thread.currentThread().getName()+"......++++"); } } public void setFlag() { flag = false; } } class StopThreadDemo { public static void main(String[] args) { StopThread st = new StopThread(); Thread t1 = new Thread(st); Thread t2 = new Thread(st); t1.start(); t2.setDaemon(true); t2.start(); int num = 1; for(;;) { if(++num==50) { t1.interrupt(); break; } System.out.println("main...."+num); } System.out.println("over"); } }
相关文章推荐
- SQL Server数据库查询速度慢的原因和解决方法
- 92. Reverse Linked List II
- Openjudge1487 Highways(prim)
- 表值参数学习
- javascript 变量 命名规范 变量的作用域
- Android应用安全之第三方SDK安全
- Android-Universal-Image-Loader的使用注意事项
- 四款PDF文档制作软件横向评测
- SpringMVC学习系列(11) 之 表单标签
- Ajax返回数据类型
- Eclipse里Tomcat启动贼慢的解决方法
- LCA算法
- 开心消消乐
- 测试城市电话号码
- Python 时间格式化
- java使用Redis3--完整模板类
- 【暑假】[实用数据结构]动态连续和查询问题
- 如何保存网页
- js获取GET数据
- Cocos2d-x 3.6 项目实战---贪吃蛇(2)