Thread的过期方法和常用方法

前言

Thread类里面有很多方法,大多数在jdk早期版本就已经存在了。有些方法,他们的命名都是非常简单易懂的,但是因为某些问题已经废弃掉了。有些方法却是很常用的。下面我们简单罗列一下:

  1. stop() // 过期方法,停止线程的执行
  2. suspend() // 过期方法,暂停线程的执行
  3. resume() // 过期方法,恢复线程的执行
  4. interrupt() // 常用方法,中断线程
  5. boolean isInterrupted() // 常用方法,返回线程是否被中断
  6. static boolean interrupted() // 常用方法,返回线程是否被中断,同时清空中断标记
  7. join() // 常用方法,等待线程结束
  8. yield() // 常用方法,让出cpu时间片
  9. sleep() // 常用方法,线程休眠
  10. holdsLock(Object obj) // 常用方法,线程是否持有锁
  11. setContextClassLoader() // 常用方法,设置线程上下文类加载器

过期方法 - stop()

/**
 * @deprecated This method is inherently unsafe.  Stopping a thread with
 *       Thread.stop causes it to unlock all of the monitors that it
 *       has locked (as a natural consequence of the unchecked
 *       <code>ThreadDeath</code> exception propagating up the stack).  If
 *       any of the objects previously protected by these monitors were in
 *       an inconsistent state, the damaged objects become visible to
 *       other threads, potentially resulting in arbitrary behavior.  Many
 *       uses of <code>stop</code> should be replaced by code that simply
 *       modifies some variable to indicate that the target thread should
 *       stop running.  The target thread should check this variable
 *       regularly, and return from its run method in an orderly fashion
 *       if the variable indicates that it is to stop running.  If the
 *       target thread waits for long periods (on a condition variable,
 *       for example), the <code>interrupt</code> method should be used to
 *       interrupt the wait.
 *       For more information, see
 *       <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
 *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
 */
@Deprecated
public final void stop() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        checkAccess();
        if (this != Thread.currentThread()) {
            security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
        }
    }
    // A zero status value corresponds to "NEW", it can't change to
    // not-NEW because we hold the lock.
    if (threadStatus != 0) {
        resume(); // Wake up thread if it was suspended; no-op otherwise
    }

    // The VM can handle all thread states
    stop0(new ThreadDeath());
}

翻译一下废弃的原因:

该方法本质上是不安全的。调用此方法会释放所有持有的监视器的锁(作为沿堆栈向上传播的未检查 ThreadDeath 异常的一个自然后果)。
如果这些监视器对象保护的数据存在不一致的状态,这些不一致的数据将对其他线程将变得可见,会导致任何可能的行为。
stop的许多使用都应由只修改某些变量以指示目标线程应该停止运行的代码来取代。目标线程应定期检查该变量,并且如果该变量指示它要停止运行,则从其运行方法依次返回。
如果目标线程等待很长时间(例如基于一个条件变量),则应使用 interrupt 方法来中断该等待。

其实原因里面说得很明白了。

  1. 废弃原因为锁对象保护的数据在调用stop方法的时候可能存在不一致的情况
  2. 解决方法为使用基于变量的方式来来stop线程,变量由外部传入,该变量通常是volatile boolean类型,且在循环里面所使用。

过期方法 - suspend() / resume()

我们使用音乐播放器播放音乐时,可以对正在播放的音乐暂停,对暂停的音乐恢复继续播放。这两个方法分别对应到暂停恢复,他们通常是成对出现的。我们看看源码上废弃的原因。

/**
 * @deprecated   This method has been deprecated, as it is
 *   inherently deadlock-prone.  If the target thread holds a lock on the
 *   monitor protecting a critical system resource when it is suspended, no
 *   thread can access this resource until the target thread is resumed. If
 *   the thread that would resume the target thread attempts to lock this
 *   monitor prior to calling <code>resume</code>, deadlock results.  Such
 *   deadlocks typically manifest themselves as "frozen" processes.
 *   For more information, see
 *   <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
 *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
 */
@Deprecated
public final void suspend() {
    checkAccess();
    suspend0();
}
/**
 * @deprecated This method exists solely for use with {@link #suspend},
 *     which has been deprecated because it is deadlock-prone.
 *     For more information, see
 *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
 *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
 */
@Deprecated
public final void resume() {
    checkAccess();
    resume0();
}

这两个方法混合使用时,存在死锁的风险。

  1. 如果目标线程持有锁,调用suspend之后,不会释放锁。
  2. 如果resume方法先于suspend方法调用,就会导致死锁

为什么会这样呢,我们写一个demo来看看。

public class BadSuspend {

    public static Object u = new Object();

    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {

        public ChangeObjectThread(String name) {
            super(name);
        }

        @Override public void run() {
            synchronized (u) {
                System.out.println("in " + getName());
                Thread.currentThread().suspend();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        // t1的start和t1的resume之间因为有sleep方法,所以resume会比suspend后执行,因此也不会出现死锁的问题
        // t2的start和t2的resume之间没有sleep方法,通常情况resume会比suspend先执行,而suspend并不会释放锁,也不会被恢复,从而出现死锁
        // t2死锁的时候我通过jps和jstack查看线程的状态,居然是Runnable,非常的坑爹!
        // t2的临时解决方法是:在t2.resume之前加入sleep
        t1.start();
        Thread.sleep(100L);
        t2.start();
        t1.resume();
        // Thread.sleep(100L);
        t2.resume();
        t1.join();
        t2.join();
    }
}
image.png

常用方法 - interrupt() / boolean isInterrupted() / static boolean interrupted()

这三个方法都和线程中断有关,中断可以代替stop来停止线程,但是停止线程的过程又由用户自己来控制,并不像stop那样暴力。

  1. interrupt() // 中断线程,这儿的中断只是给线程打一个中断的标记,并不会真正地使线程退出。线程的退出仍然由用户来控制
  2. boolean isInterrupted() // 判断线程是否是中断的,该方法可以重复调用,而不会清除掉线程的中断标记
  3. static boolean interrupted() // 判断线程是否是中断的,同时清除线程的中断标记(这点和boolean isInterrupted()有所不同)

还是写一些demo来看看效果吧。

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(() -> {
        for (; ; ) {
        }
    });

    t1.start();
    Thread.sleep(1000);
    t1.interrupt();
    System.out.println("main stopped");
}

我们直接写一个for循环,main线程会调用interrupt,但是我们发现t1线程并没有退出,这是因为interrupt只会给线程设置一个中断标记,并不会真正地中断线程,而是需要用户自己来选择,在合适的时机来做处理。我们实际开发中不要这样写!

修改后的代码如下

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(() -> {
        for (; ; ) {
            if (Thread.currentThread().isInterrupted()) {
                break;
            }
        }
        System.out.println("ended");
    });

    t1.start();
    Thread.sleep(1000);
    t1.interrupt();
    System.out.println("main stopped");
}

我们另外再看看interrupted方法。通过以下的方式,我们可以看出interrupted会清除中断标记

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(() -> {
        for (; ; ) {
            if (Thread.interrupted()) {
                System.out.println("is interrupted: " + Thread.currentThread().isInterrupted());
                break;
            }
        }
        System.out.println("ended");
    });

    t1.start();
    Thread.sleep(1000);
    t1.interrupt();
    System.out.println("main stopped");
}

另外,在我们的代码中如果有调用sleep或者wait方法,这两个方法在中断的时候会清除中断标记,同时抛出InterruptedException异常。还是以实际demo为例。

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(() -> {
        for (; ; ) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("interrupted status: " + Thread.currentThread().isInterrupted());
                break;
            }
        }
    });

    t1.start();
    Thread.sleep(1000);
    t1.interrupt();
    System.out.println("main stopped");
}

常用方法 - join()

/**
 * Waits for this thread to die.
 *
 * <p> An invocation of this method behaves in exactly the same
 * way as the invocation
 *
 * <blockquote>
 * {@linkplain #join(long) join}{@code (0)}
 * </blockquote>
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public final void join() throws InterruptedException {
    join(0);
}

字面意思很简单,等待线程直到死,够直接的哈!
这个方法一般在一个线程需要另一个线程结果的时候使用。那么这个方法内部又是怎么实现的呢?我们分析一下源码。

public final synchronized void join(long millis)
throws InterruptedException {
    // 获取当前时间,设置为base
    long base = System.currentTimeMillis();
    long now = 0;
    
    // 如果等待的毫秒数是负数,则传入参数有问题,抛出异常
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    // 传入的参数为0,则一直循环判断当前线程是否是活着,活着的话就wait(0),直到另外一个线程notify当前线程
    if (millis == 0) {
        // isAlive()就是线程start之后,且还没有死亡
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            // 带超时时间的wait
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}

源码还是蛮简单的,内部实现是通过wait()wait(long timeout)来实现的。我们还是写一个demo来验证一下这个方法的用法吧。

public class JoinMain {

    public volatile static int i = 0;

    public static class AddThread extends Thread {

        @Override public void run() {
            for (i = 0; i < 1000000; i++) {
            }
        }
    }

    public static void main(String[] args) throws Exception {
        AddThread at = new AddThread();
        at.start();
        at.join();
        System.out.println(i);
    }
}

这段代码最终打印的结果一定是1000000!

常用方法 - yield()

这个方法比较简单,就是让出cpu时间片,让其他线程执行。

/**
 * A hint to the scheduler that the current thread is willing to yield
 * its current use of a processor. The scheduler is free to ignore this
 * hint.
 *
 * <p> Yield is a heuristic attempt to improve relative progression
 * between threads that would otherwise over-utilise a CPU. Its use
 * should be combined with detailed profiling and benchmarking to
 * ensure that it actually has the desired effect.
 *
 * <p> It is rarely appropriate to use this method. It may be useful
 * for debugging or testing purposes, where it may help to reproduce
 * bugs due to race conditions. It may also be useful when designing
 * concurrency control constructs such as the ones in the
 * {@link java.util.concurrent.locks} package.
 */
public static native void yield();

常用方法 - sleep()

该方法的意思为使线程休眠一段时间,休眠的线程,其状态为TIMED_WAITING。该方法在Thread里面有两个重载方法

  1. public static native void sleep(long millis) throws InterruptedException;
  2. public static void sleep(long millis, int nanos) throws InterruptedException;

我们剖析一下源码

/**
 * 1. 让当前线程休眠一定时间(暂停执行)
 * 2. 线程不会释放锁
 * 3. 纳秒其实并不是真正的纳秒休眠,而是将纳秒进行四舍五入
 * 
 * Causes the currently executing thread to sleep (temporarily cease
 * execution) for the specified number of milliseconds plus the specified
 * number of nanoseconds, subject to the precision and accuracy of system
 * timers and schedulers. The thread does not lose ownership of any
 * monitors.
 *
 * @param  millis
 *         the length of time to sleep in milliseconds
 *
 * @param  nanos
 *         {@code 0-999999} additional nanoseconds to sleep
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative, or the value of
 *          {@code nanos} is not in the range {@code 0-999999}
 *
 * // InterruptedException,如果有其他线程中断当前线程,则抛出此异常。异常抛出之后,当前线程的中断标记会被清除。
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public static void sleep(long millis, int nanos) throws InterruptedException {
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }

    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis++;
    }

    sleep(millis);
}

常用方法 - holdsLock()

/**
 * 当前线程持有指定对象的监视器锁,才会返回true,否则返回false。
 *
 * Returns <tt>true</tt> if and only if the current thread holds the
 * monitor lock on the specified object.
 *
 * <p>This method is designed to allow a program to assert that
 * the current thread already holds a specified lock:
 * <pre>
 *     assert Thread.holdsLock(obj);
 * </pre>
 *
 * @param  obj the object on which to test lock ownership
 * @throws NullPointerException if obj is <tt>null</tt>
 * @return <tt>true</tt> if the current thread holds the monitor lock on
 *         the specified object.
 * @since 1.4
 */
public static native boolean holdsLock(Object obj);

常用方法 - setContextClassLoader()

这个方法在很多框架代码里经常出现。为什么呢?

  1. 类加载机制里面的双亲委派机制
  2. 什么时候会违背双亲委派机制
  3. 这个方法如何解决未被双亲委派机制场景下的问题

我们会单独写一篇博客来说明一下类加载机制。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容