正确结束Java Thread的方法

来源:互联网 发布:安卓时间校准软件 编辑:程序博客网 时间:2024/05/16 01:31

stop()方法非常坑爹,早已不提倡使用,单纯使用interrupt()也不安全。


package thread;public class StopThreadTest {    /**     * @param args     * @throws InterruptedException      */    public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubTheadToStop th = new TheadToStop();System.out.println(Thread.currentThread().getName() + " stating a new thread");th.start();Thread.sleep(300);System.out.println(Thread.currentThread().getName() + " interrupt the thread");th.interrupt();Thread.sleep(400);System.out.println(Thread.currentThread().getName() + " stop main");    }    }class TheadToStop extends Thread{        //共享变量    private volatile boolean isStop = false;        @Override    public void interrupt(){//调用interrupt之前,把isStop置为falseisStop = true;super.interrupt();    }        @Override    public void run(){System.out.println(Thread.currentThread().getName() + " is going to run");// double check,检查stop的状态 while(!isStop){    System.out.println(Thread.currentThread().getName() + " is running");    try {Thread.sleep(400);    } catch (InterruptedException e) {  System.out.println(Thread.currentThread().getName() + " is interrupt");    }}System.out.println(Thread.currentThread().getName() + " is exiting");    }}