并发编程系列(二)线程的中断

线程中断的概念

java中线程中断是一种协作机制
通过中断并不能直接终止线程的运作
需要被中断的线程自己处理中断.
每个线程都有一个boolean类型的标志位,代表线程是否中断;

线程1想中断线程2,线程1只需要设置线程2的中断标识位等于true即可;

线程2在合适的时候处理中断请求,甚至线程2可以选择不处理中断请求;

结论:设置线程中断后,被中断的线程不是立即停止运行状态。

线程中断的相关方法

1:public static boolean interrupted()

    /**
     * Tests whether the current thread has been interrupted.  The
     * <i>interrupted status</i> of the thread is cleared by this method.  In
     * other words, if this method were to be called twice in succession, the
     * second call would return false (unless the current thread were
     * interrupted again, after the first call had cleared its interrupted
     * status and before the second call had examined it).
     *
     * <p>A thread interruption ignored because a thread was not alive
     * at the time of the interrupt will be reflected by this method
     * returning false.
     *
     * @return  <code>true</code> if the current thread has been interrupted;
     *          <code>false</code> otherwise.
     * @see #isInterrupted()
     * @revised 6.0
     */
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

测试当前线程是否已中断。线程的中断状态由该方法清除

如果连续调用两次该方法,则第二次调用将返回false,在第一次调用已清除了其中中断状态,且第二次调用检验中断状态前,可以对当前线程再次中断。

2:public boolean isInterrupted()

  /**
     * Tests whether this thread has been interrupted.  The <i>interrupted
     * status</i> of the thread is unaffected by this method.
     *
     * <p>A thread interruption ignored because a thread was not alive
     * at the time of the interrupt will be reflected by this method
     * returning false.
     *
     * @return  <code>true</code> if this thread has been interrupted;
     *          <code>false</code> otherwise.
     * @see     #interrupted()
     * @revised 6.0
     */
    public boolean isInterrupted() {
        return isInterrupted(false);
    }

测试线程是否已经中断,线程的中断状态不受该方法的影响

3:public void 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();
    }

这个方法是唯一能将中断状态设置为true的方法,静态方法interrupted()会将当前线程的状态清除。

方法中会抛出 InterruptedException 则表示该方法是可中断
常见的抛出InterruptedException 的方法:

object.wait();
Thread.sleep();
BlockQueue.put();
BlockQueue.take();


参考书籍:《并发编程的实战》

发布了12 篇原创文章 · 获赞 0 · 访问量 337

猜你喜欢

转载自blog.csdn.net/fd135/article/details/104378710
今日推荐