对线程interrupt的初浅理解

  在java中,使用interrrupt可以用来请求中止线程。对一个线程调用interrrupt方法时,该线程的中断状态位被置位,每个线程不断访问自己的这个标志,以判断线程是否被中断(只是要求java开发者去添加的判断,并不在内部实现)。可以调用Thread的方法isInterrupted判断是否线程中断,代码如下:


//5s后interrup请求打印一个异常
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Hello World");
            }
        });

        thread.start();
        try {
            Thread.sleep(5000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

线程在5s后得到中断请求,中断。停止打印。

如果线程被阻塞,处于sleep或wait状态,则在请求该线程中断时,会抛出InterruptedException,代码如下:


//5s后interrup请求打印一个异常
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(()->{
            while(!Thread.currentThread().isInterrupted()){
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Hello World");
            }
        });

        thread.start();
        try {
            Thread.sleep(5000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值