Java多线程的中断

运行中的中断

1. 使用Thread.interrupted()

静态方法调用一次后会清除标志。

        // no
        System.out.println(Thread.interrupted());

        // interrupt
        Thread mainThread = Thread.currentThread();
        mainThread.interrupt();

        // yes and clear
        System.out.println(Thread.interrupted());

        // no
        System.out.println(Thread.interrupted());

2. 使用object.isInterrupted()

实例方法不会清除标志。

        // interrupt
        Thread mainThread = Thread.currentThread();

        // no
        System.out.println(mainThread.isInterrupted());
        
        mainThread.interrupt();

        // yes and not clear
        System.out.println(mainThread.isInterrupted());

        // yes
        System.out.println(mainThread.isInterrupted());

 

阻塞时中断

public class BlockedInterrupted {
        
        public static void main(String[] args) {
                Thread t = new Thread(BlockedInterrupted::run); 
                t.start();
                // main thread sleeps for 5 seconds
                try {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // Interrupt the sleeping thread 
                t.interrupt();
         }

        public static void run() { 
            int counter = 1;
            while (true) {
                try {
                    Thread.sleep(1000); 
                    System.out.println("Counter:" + counter++);
                }
                catch (InterruptedException e) {
                    System.out.println("I got interrupted!");
                    return;
                }
            }
        }

}

阻塞时的中断不会改变标志,而是引发一个InterruptedException异常,捕获异常退出即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值