记录java线程中断理解,Thread.currentThread().interrupt();

记录java线程中断理解,Thread.currentThread().interrupt();

一、概述

中断的理解:

1、Java 线程中断,协作式(通过 Thread.interrupt() 触发,需代码显式检查中断状态或调用可中断方法)。
2、操作系统中断线程(如 Linux 的 kill -9 或强制终止线程)。

二、代码中的应用

以下对中断的描述,场景都是java中,线程协作中断。可以理解为:
当使用线程异步执行方法时,假设这个方法运行1天,那你想提前终止这个方法,就可以调用这个线程的interrupt()方法,触发中断通知,也就是告诉这个线程终止任务,注意这里只是发送了一个取消信号,至于是否取消,要看方法是否检查了取消信号,并做了终止方法处理。

用代码来说就是有2个场景:

一,不响应中断(就是你通知你的,我执行我的)

这个main方法是不会跳出的,不会打印 【执行完成】

public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(1);
        Thread thread = new Thread(() -> {
            long i = 0L;
            while (i >= 0L) {
                i++;
                i--;
            }
            latch.countDown();
        });

        thread.start();
        System.out.println("线程启动");

        thread.interrupt();
        System.out.println("触发线程中断命令");

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("执行完成");
    }

输出结果:
在这里插入图片描述

在这里插入代码片

二,响应中断(检查到中断通知,跳出任务执行)

public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(1);
        Thread thread = new Thread(() -> {
            long i = 0L;
            while (i >= 0L) {
                i++;
                i--;
                if (Thread.interrupted()) {
                    System.out.println("检查到中断,跳出循环");
                    break;
                }
            }
            latch.countDown();
        });

        thread.start();
        System.out.println("线程启动");

        thread.interrupt();
        System.out.println("触发线程中断命令");

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("执行完成");
    }

输出结果:

在这里插入图片描述

在AQS中的应用:

粗略的看一下,提供了2种类型的方法。
不检查中断
检查中断
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值