结束线程常用方法

结束线程

1、通过结束run函数从而结束线程

public class CloseThread {

    private static class Worker extends Thread {
        private volatile boolean start = true;

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (start) {

            }
        }

        public void shutdown() {
            this.start = false;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Worker wk = new Worker();
        wk.start();

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        wk.shutdown();

    }       
}

2、 通过捕获异常然后退出run方法

public class CloseThread {

    private static class Worker extends Thread {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Worker wk = new Worker();
        wk.start();

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        wk.interrupt();

    }       
}

猜你喜欢

转载自www.cnblogs.com/Stephanie-boke/p/12319848.html