Java并发编程基础-理解中断

章节

  • 什么是中断
  • 中断线程的方法
  • 线程中断状态的判断以及何时被中断的线程所处 isInterrupted() 状态为 false?
1.什么是中断

线程标识位

中断可以理解为线程的一个标识位属性,它标识一个运行中的线程是否被其他线程进行了中断操作。
2.中断线程的方法
其他线程通过调用该线程的 interrupt() 方法对其进行中断操作。
其实就是其他线程对该线程打了个招呼,要求其中断。
3. 线程中断状态的判断
线程通过方法isInterrupted()方法来进行判断是否被中断。

如下两种情况需要注意:

1.如果被中断的线程已经处于终结状态,那么调用该线程对象的 thread.isInterrupted() 返回的仍是 false。
2.在Java API中可以看到,许多抛出 InterruptedException 的方法,(其实线程已经终结了,因为遇到了异常)如Thread.sleep( long mills) 方法)这些方法在抛出InterruptedException 异常之前,JVM会将中断标识位清除,然后抛出InterruptedException,此时调用isInterrupted()仍会返回false。

package org.seckill.Thread;

import java.util.concurrent.TimeUnit;

public class Interrupted {

    public static void main(String[] args) throws InterruptedException{
        Thread sleepThread = new Thread(new SleepRunner(),"sleepRunner");
        sleepThread.setDaemon(true);//支持性线程
        Thread busyThread = new Thread(new BusyRunner(),"busyRunner");
        busyThread.setDaemon(true);

        sleepThread.start();
        busyThread.start();

        TimeUnit.SECONDS.sleep(5);

        sleepThread.interrupt();
        busyThread.interrupt();

        System.out.println("sleep Thread interrupted status is:"+sleepThread.isInterrupted());
        System.out.println("busy Thread interrupted status is:"+busyThread.isInterrupted());

        SleepUnit.second(500);

    }

    /**
     * 沉睡中的线程-静态内部类
     */
    static class SleepRunner implements Runnable {
        public void run() {
            while (true) {
                SleepUnit.second(10);
            }
        }
    }

    /**
     * 不停运行,空耗cpu的线程-静态内部类
     */
    static class BusyRunner implements Runnable {
        public void run() {
            while (true) {

            }
        }
    }

    /**
     * 静态内部工具类
     */
    static class SleepUnit {
        public static void second(int seconds) {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:


img_26dda2654df36e2e44ee1911575b94fa.png
运行结果

我们可以发现 sleep线程的 isInterrupted 状态为false,其中断标识位被清除了。
busy 线程属于正常中断所以isInterrupted 状态为 true,中断标识位没有被清除。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值