二、怎么停止一个java线程

1. 错误的停止方式
  1. stop()(已经废弃)
    原因是stop会在线程没有执行完的时候强行停止线程,清除监视器锁的信息,如果一个线程计算一项工作完成一半突然停止,有可能导致数据不一致,与我们的期望不一致,可能导致线程安全问题
package com.example.thread;

public class StopThread extends Thread {
    private int i = 0, j = 0;

    @Override
    public void run() {
    	//增加同步锁,保证线程安全
        synchronized (this) {
            ++i;
            try {
                //休眠10s模拟耗时操作
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++j;
        }
    }

    public void print() {
        System.out.println("i=" + i + ",j=" + j);
    }

    public static void main(String[] args) throws InterruptedException {
        StopThread thread = new StopThread();
        thread.start();
        //休眠1s,确保变量自增成功
        Thread.sleep(1000);
        //中止线程
        thread.stop();
        while (thread.isAlive()) {
            //确保线程已经终止
        }
        //输出结果
        thread.print();
        //实际输出 :i=1,j=0
    }
}

  1. 我们可以利用 thread.interrupt(); 或者 flag标志位去停止线程
    1. 利用thread.interrupt();
package com.example.thread;

public class InterruptThread extends Thread {
    private int i = 0, j = 0;

    @Override
    public void run() {
        //增加同步锁,保证线程安全
        synchronized (this) {
            ++i;
            try {
                //休眠10s模拟耗时操作
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++j;
        }
    }

    public void print() {
        System.out.println("i=" + i + ",j=" + j);
    }

    public static void main(String[] args) throws InterruptedException {
        InterruptThread thread = new InterruptThread();
        thread.start();
        //休眠1s,确保变量自增成功
        Thread.sleep(1000);
        //中止线程
        thread.interrupt();
        while (thread.isAlive()) {
            //确保线程已经终止
        }
        
        thread.print();
       /*  输出结果 
        java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at com.example.thread.InterruptThread.run(InterruptThread.java:13)
        
        i=1,j=1
       
       */

    }
}

  1. 利用标志位,如果我们业务中有while循环,我们可以声明一个volatile变量的编制为flag=false,然后当条件达到时,在主线程中设置flag=true,停止子线程的运行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值