Java安全停止线程方法

来源:互联网 发布:java语言培训机构 编辑:程序博客网 时间:2024/06/07 15:35

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 plaincopy
  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 plaincopy
  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. }