现在的位置: 首页 > 综合 > 正文

Java安全停止线程方法

2013年12月13日 ⁄ 综合 ⁄ 共 989字 ⁄ 字号 评论关闭

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() {  

抱歉!评论已关闭.