[Java]interrupt()用法

一、源码阅读

1 interrupt()

Thread#interrupt()的作用其实也不是中断线程,而是通知线程应该中断了,具体来说,当对一个线程调用interrupt() 时:

  • 如果线程处于被阻塞状态(例如处于sleep, wait, join 等状态),那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常,仅此而已。

  • 如果线程处于正常活动状态,那么会将该线程的中断标志设置为true,仅此而已。被设置中断标志的线程将继续正常运行,不受影响。

interrupt() 并不能真正的中断线程,需要被调用的线程自己进行配合才行,在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程。具体到底中断还是继续运行,应该由被通知的线程自己处理。

public void interrupt() {

        if (this != Thread.currentThread())

            checkAccess();

 

        synchronized (blockerLock) {

            Interruptible b = blocker;

            if (b != null) {

                interrupt0();           // Just to set the interrupt flag

                b.interrupt(this);

                return;

            }

        }

        interrupt0();  // Just to set the interrupt flag

    }

2 interrupted()

检查当前中断标识(即查看当前中断信号是true还是false),并清除中断信号。一般处理过中断以后使用此方法。

    public static boolean interrupted() {

        return currentThread().isInterrupted(true);

    }

    /**

     * Tests if some Thread has been interrupted.  The interrupted state

     * is reset or not based on the value of ClearInterrupted that is

     * passed.

     */

    private native boolean isInterrupted(boolean ClearInterrupted);

3 isInterrupted()

检查当前中断标识(即查看当前中断信号是true还是false)

public boolean isInterrupted() {

    return isInterrupted(false);

}

二 、示例

以下示例展示了通过isInterrupted()、interrupt()如何终止执行中的线程,如下所示代码中中创建了两个线程(thread1、thread2),thread1每隔500ms数数一次,thread2休眠一段时间以后中断thread1,thread1将会终止。

import java.util.Random;

/**
 * @author Leon
 * @create 2019-07-26-15:02
 */
public class Thread1 {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            try {
                int i = 0;
                while (!Thread.currentThread().isInterrupted()) {
                    Thread.sleep(500);
                    System.out.println("couting... i=" + i);
                    i++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("thread1 interrupted");
            }
        });
        Thread thread2 = new Thread(() -> {
            Random random = new Random();
            try {
                long time = random.nextInt(3000) + 1000;
                Thread.sleep(time);
                System.out.println("interrupt thread1");
                thread1.interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
        thread2.start();
    }
}


提示:如果代码报错提示Lambda expressions are not supported at language level ‘5’,则修改modules如下所示:
在这里插入图片描述
运行结果:
在这里插入图片描述
参考文章:https://yq.aliyun.com/articles/680328

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值