多线程之线程终止

本文探讨了在Java中如何终止线程,包括使用自定义标识符和调用interrupt()方法。同时,解释了interrupted()和isinterrupted()的区别,强调了中断标识符的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于线程终止:李四一旦进到工作状态,他就会按照行动指南上的步骤去进行工作,不完成是不会结束的。但有时我们 需要增加一些机制,例如老板突然来电话了,说转账的对方是个骗子,需要赶紧停止转账,那张三该如 何通知李四停止呢?这就涉及到我们的停止线程的方式了。

线程终止的方法:

1、使用自定义标识符来终止线程(需要给标志位上加 volatile 关键字)

public class CsdnDemo {
    //1.声明一个自定义标识符
    private volatile static boolean flag = false;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            while (!flag){
                System.out.println("正在转账...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("差点误了大事");
        });
        thread.start();

        Thread.sleep(3000);
        //终止线程
        System.out.println("停止交易");
        flag = true;
    }
}

 

2、调用 interrupt() 方法来通知

public class CsdnDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            while (!Thread.interrupted()){//两种方式皆可
                //           while (!Thread.currentThread().isInterrupted()){
                System.out.println("正在转账...");
            }
            System.out.println("差点误了大事");
        });
        thread.start();
        Thread.sleep(100);
        //终止线程
        thread.interrupt();
        System.out.println("终止交易");
    }
}

interrupted和isinterrupted的区别

1、interrupted属于静态方法,所有程序都可以直接调用的全局方法,而isinterrupted属于某个实例       的方法。

2、interrupted在使用完之后会重置中断标识符,而isinterrupted不会重置中断表示。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值