首页 > 编程语言 > 详细

结束线程常用方法

时间:2020-02-17 09:45:36      阅读:67      评论:0      收藏:0      [点我收藏+]

结束线程

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

    }       
}

结束线程常用方法

原文:https://www.cnblogs.com/Stephanie-boke/p/12319848.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!