JAVA 线程停止

之前使用过sleep来停止线程

我们这次使用别的方法来停止线程

//测试线程停止
//1.建议线程正常停止-----利用次数,不建议死循环
//2.建议使用标志位-------设置一个标志位
//3.不要使用stop,destroy等过时或JDK不建议的方法
public class TestStop implements Runnable{
    //设置一个标志位
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("the thread is runing...."+i++);
        }
    }
    //设置一个停止方法
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 100; i++) {
            System.out.println("this is main thread "+i);
            if (i == 50){
                testStop.stop();
                System.out.println("the thread is stop.");
            }
        }
    }
}

执行结果如下:

可以看到,当主线程到50时,我们更改了run线程的标志位 使它停止  此时run线程跑到了93的地方,主线程并没有停止,他要跑完了才不跑

使用标志位来停止线程,是一个比较建议的做法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值