多线程----interrupt、interrupted、isInterrupted

java的多线程中断方式是interrupt

该方法没有被static修饰是一个运行时方法,被用来中断指定的线程,使用方式也简单,在线程对象后面直接调用该方法就行比如说

MyThread2 thread = new MyThread2();
thread.start();
Thread.sleep(10);
thread.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();
    }

在调用该方法后首先检查是不是当前线程,如果不是调用checkAccess()方法检查这个线程的权限,如果是则首先获取blockerLock这个锁保证可以安全的访问下面的代码。其中blockerLock在源码中是这样定义,意思是如果被中断的线程中有可中断的IO操作则在设置此线程的中断状态后,应调用拦截器的中断方法。


    /* The object in which this thread is blocked in an interruptible I/O
     * operation, if any.  The blocker's interrupt method should be invoked
     * after setting this thread's interrupt status.
     */
    private volatile Interruptible blocker;
    private final Object blockerLock = new Object();

如果中断标志不为null则调用interrupt0()设置中断标志位,设置完成就返回。

interrupted是判断中断标志的一个方法,被static修饰,是判断当前线程是否被中断,而且在检查完后会清除标志位。

public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

isInterrupted是另一个中断标志位,是测试线程Thread对象是否处于中断状态,而且由于传入的参数是false标志不会清除中断标志位。

    public boolean isInterrupted() {
        return isInterrupted(false);
    }

其中isInterrupted是一个本地方法,用c++编写用来检查中断标志的。

private native boolean isInterrupted(boolean ClearInterrupted);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值