Concurrency:wait及sleep方法分析

方法声明
java.lang.Thread public static void sleep(long millis)
throws InterruptedException

导致当前的执行线程睡眠(暂时停止执行)指定的毫秒数 取决于系统定时器和调度器的精度和准确度 这个线程不会放弃对于任何监视器(call it 锁)的所有权
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Params:
millis – the length of time to sleep in milliseconds
Throws:
IllegalArgumentException – if the value of millis is negative
InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.


方法声明
java.lang.Thread public static void sleep(long millis,
int nanos)
throws InterruptedException

这个方法同上个方法相比 会增加一个纳秒的参数
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.

Params:
millis – the length of time to sleep in milliseconds
nanos – 0-999999 additional nanoseconds to sleep
Throws:
IllegalArgumentException – if the value of millis is negative, or the value of nanos is not in the range 0-999999
InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

public static void sleep(long millis, int nanos)
    throws InterruptedException {

        //等待的时间不能<0
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        //调整的纳秒参数不能<0或者是>999999
        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }
        
        //调整的nanos>500000或者nanos!=0&&mills==0
        millis自增一下
        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

wait方法和sleep方法的区别:

sleep method 是用于暂停进程的执行几秒或者其他的时间我们想要指定的时间
但是一旦调用了wait method 线程将会处于等待状态不会自动的恢复直到调用了notify或者是notifyAll方法
sleep() is a method which is used to pause the process for few seconds or the time we want to. But in case of wait() method, thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

wait及sleep方法的主要的不同是 wait会释放掉锁或者监视器 但是sleep在等待的过程中不会释放锁或者监视器 wait方法用于线程的内部通信 sleep方法通常用于运行时暂停执行
The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases the lock or monitor while waiting. wait() is used for inter-thread communication while sleep() is used to introduce pause on execution, generally.

Thread.sleep 将当前的线程调整到非运行时状态一段时间,这个线程保持拥有对象锁的状态 如果当前的线程在一个同步代码块或者方法(没有线程可以进入这个方法或者代码块)如果其他的线程调用了intertupt() 将唤醒等待的线程。
Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt(). it will wake up the sleeping thread.

sleep时一个静态方法 意味着它可以总是影响当前的线程(执行sleep方法的线程),通常错误的认为调用t.sleep()(但是t不是当前正在执行的线程)即使这样,也将休眠的是当前线程,而不是t线程
While sleep() is a static method which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.


未持有锁的线程直接调用wait()会发生什么情况?

public class MyTest1 {

  public static void main(String[] args) throws InterruptedException {
    Object object=new Object();
    object.wait();
  }

}

Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at com.compass.spring_lecture.thread.MyTest1.main(MyTest1.java:10)


必须要在synchronized代码块中或者instance method、static method
在调用wait方法时,线程必须要持有对象的锁,当调用wait方法时,线程就会释放掉对象的锁 在调用Thread类的sleep方法时,线程时不会释放掉对象的锁

public class MyTest1 {

  public static void main(String[] args) throws InterruptedException {
    Object object = new Object();
    synchronized (object) {
      object.wait();
    }
  }
}

反编译MyTest.class 并简单的查看一下信息

C:\spring_lecture\target\classes\com\compass\spring_lecture\thread>javap -c  MyTest1

public class com.compass.spring_lecture.thread.MyTest1 {
  public com.compass.spring_lecture.thread.MyTest1();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]) throws java.lang.InterruptedException;
    Code:
       0: new           #2                  // class java/lang/Object
       3: dup
       4: invokespecial #1                  // Method java/lang/Object."<init>":()V
       7: astore_1
       8: aload_1
       9: dup
      10: astore_2

      11: monitorenter//进入 持有对象的锁 synchronized
      12: aload_1
      13: invokevirtual #3                  // Method java/lang/Object.wait:()V
      16: aload_2
      17: monitorexit//正常退出

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

推荐阅读更多精彩内容