zoukankan      html  css  js  c++  java
  • Java安全停止线程方法

      1. 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. 2.使用volatile变量来设置Thread的run的循环条件,保证变量同步性  
      3.       
      4. public class JavaTest extends Thread{  
      5. private volatile boolean isRun = true;  
      6. public static void main(String[] args) {  
      7. JavaTest thread = new JavaTest();  
      8. thread.start();  
      9. thread.close();  
      10. }  
      11. @Override  
      12. public void run() {  
      13. while (isRun) {  
      14. //dosomething  
      15. }  
      16. }  
      17. public void close() {  
      18. this.isRun = false;  
      19. }  
      20. }  
      21. 3.使用interrupt()来中止非运行状态的线程,如wait()和sleep()状态的线程,此时可利用interrupted来终止线程  
      22. public class JavaTest extends Thread{  
      23. private volatile boolean isRun = true;  
      24. public static void main(String[] args) {  
      25. JavaTest thread = new JavaTest();  
      26. thread.start();  
      27. thread.close();  
      28. if (thread != null) {  
      29. thread.interrupt(); //外围调用关闭  
      30. }  
      31. }  
      32. @Override  
      33. public void run() {  
      34. while (isRun) {  
      35. //dosomething  
      36.   
      37. try {  
      38. wait();   //同样适用于sleep等状态  
      39. catch (InterruptedException e) {  
      40. //catch Exception  
      41. }  
      42. }  
      43. }  
      44. public void close() {  
      45. this.isRun = false;  
      46. }  

  • 相关阅读:
    第二阶段:冲刺2(个人界面的优化---头像上传)
    第二阶段:冲刺1(任务的分配)
    学习进度第12周
    读书笔记《人月神话》1
    学习进度第11周
    读书笔记《编程珠矶》3
    学习进度第10周
    第一阶段:冲刺10(完结)
    第十五周学习进度总结
    第十四周学习进度总结
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/3465082.html
Copyright © 2011-2022 走看看