127-wait和sleep的本质区别是什么,深入分析(面试常见问题)

The difference of sleep and wait:

  1. sleep is the method of Thread, but wait is the method of Object.
  2. sleep will not release the Object monitor(LOCK), but the wait will be release the monitor and add to the Object monitor waiting queue.
  3. Use sleep not depend on the monitor(synchronized), but wait need.
  4. The sleep method not need be wakeup, but wait need. except wait(long timeout)

验证不同点3:

public static void m1() {
    Thread.sleep(2_000);
}
public static void m2() {
    synchronized (LOCK) {
        LOCK.wait();
    }
}

LOCK.wait();没有使用synchronized则会抛出java.lang.IllegalMonitorStateException异常

验证不同点2:

// 两个线程依次运行
public static void m3() {
    synchronized (LOCK) {
        System.out.println("The Thread " + Thread.currentThread().getName() + " enter.");
        Thread.sleep(20_000);
    }
}
// 两个线程几乎同时运行,两个线程最终都加入到了LOCK的waiting queue
public static void m4() {
    synchronized (LOCK) {
        System.out.println("The Thread " + Thread.currentThread().getName() + " enter.");
        LOCK.wait();
    }
}
public static void main(String[] args) {
    Stream.of("T1", "T2").forEach(name -> new Thread(DifferenceOfWaitAndSleep::m4, name).start());
}

使用sleep()两个线程将会依次运行;使用wait()两个线程几乎同时运行,最终都加入到了LOCK的waiting queue


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 tuyrk@qq.com

文章标题:127-wait和sleep的本质区别是什么,深入分析(面试常见问题)

文章字数:244

本文作者:神秘的小岛岛

发布时间:2019-12-01, 16:15:27

最后更新:2019-12-01, 17:07:08

原始链接:https://www.tuyrk.cn/wang-thread/127-wait-sleep/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏