0
点赞
收藏
分享

微信扫一扫

线程停止的方式

无聊到学习 2022-04-02 阅读 51

1.线程正常停止

建议让线程正常停止,用for循环限制次数,死循环会让CPU满。

2.使用标志位

设置一个标志位,利用条件进行判断,当不满足条件时,停止线程

public class StopTest implements Runnable{
    //设置标志位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        //当标志位为true时,线程运行
        while (flag){
            System.out.println("线程运行。。"+(i++));
        }
    }

    //设置一个公有方法停止线程,转换标志位,注意:这里的stop()方法不是Thread的,是我们自己定义的
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        StopTest stopTest = new StopTest();
        new Thread(stopTest).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("主线程"+i);
            if (i == 900){
                //调用stop()方法切换标志位,停止线程
                stopTest.stop();
                System.out.println("线程停止");
            }
        }
    }
}

 

3.不建议使用JDK提供的stop()、destory()等方法(已废弃)

举报

相关推荐

0 条评论