java多线程-interrupt()

interrupt之中断状态标记
interrupt中断机制中有如下方法:
- Thread.interrupt(),设置当前中断标记为true(类似属性的set方法)
- Thread.isInterrupted(),检测当前的中断标记(类似属性的get方法)
- Thread.interrupted(),检测当前的中断标记,然后重置中断标记为false(类似属性的get方法+set方法)
因此interrupt中断机制并不是真正的将当前线程中断,而是一个中断标记的变化

示例:

public class InterruptTest {
    private static class Thread1 extends Thread {

        @Override
        public void run() {

            long time = System.currentTimeMillis();

            int num = 0;
            while (true) {
                num++;

                //1 跳出while循环
                if (isInterrupted()) {
                    System.out.println("当前线程 isInterrupted");
                    break;
                }
                if (num % 100 == 0) {
                    System.out.println(num + "     时间:" + (System.currentTimeMillis() - time));
                }
                // 3 调用sleep后要捕获InterruptedException作出相应处理
                //   因为不处理的话 isInterrupted永远会false,导致无法跳出此while循环
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.start();

        //2 延时调用interrupt中断改变interrupt状态为true
        try {
            Thread.sleep(3000);
            thread1.interrupt();
            System.out.println("执行中断");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值