说到中断线程,第一反应肯定是使用 interrupt(),但是需要注意的是,使用该方法并不会马上中断线程。。。。。

先来了解下如何判断一个线程被中断了:

    /**
     * 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);
    }
interrupted()是一个静态方法。。。。。特么一开始没注意,用线程的实例去调用,不会出错,但是结果都是没中断。。。
   /**
     * 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);
    }

注意到最后都会调用 isInterrupted(bool b) 这个布尔类型的变量代表什么什么意思呢?

The <i>interrupted status</i> of the thread is cleared by this method. 如果为真,线程中断状态会被该方法清除,换句话说,如果调用两次的话,第一次返回true,第二次返回false

建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止事件得以传播。
posted on 2016-09-29 13:21  向着大牛奋斗  阅读(222)  评论(0编辑  收藏  举报