Java安全停止线程方法

1.早期Java提供java.lang.Thread类型包含了一些列的方法start()stop()stop(Throwable) and suspend()destroy() and resume()。,Sun公司的一篇文章《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? 》

2.使用volatile变量来设置Thread的run的循环条件

    

[java]  view plain copy
  1. public class JavaTest extends Thread{  
  2.     private volatile boolean isRun = true;  
  3.     public static void main(String[] args) {  
  4.         JavaTest thread = new JavaTest();  
  5.         thread.start();  
  6.         thread.close();  
  7.     }  
  8.     @Override  
  9.     public void run() {  
  10.         while (isRun) {  
  11.             //dosomething  
  12.         }  
  13.     }  
  14.     public void close() {  
  15.         this.isRun = false;  
  16.     }  
  17. }  
3.使用interrupt()来中止非运行状态的线程,如wait()和sleep()状态的线程

[java]  view plain copy
  1. public class JavaTest extends Thread{  
  2. private volatile boolean isRun = true;  
  3. public static void main(String[] args) {  
  4. JavaTest thread = new JavaTest();  
  5. thread.start();  
  6. thread.close();  
  7. if (thread != null) {  
  8. thread.interrupt(); //外围调用关闭  
  9. }  
  10. }  

  11. @Override  
  12. public void run() {  
  13. while (isRun) {  
  14. //dosomething   

  15. try {  
  16. wait();   //同样适用于sleep等状态  
  17. catch (InterruptedException e) {  
  18. //catch Exception  
  19. }  
  20. }  
  21. }  

  22. public void close() {  
  23. this.isRun = false;  
  24. }  
  25. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值