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