17.3 睡眠和退出(Sleep and Yield )

17.3 Sleep and Yield 睡眠和退出

Thread.sleep会导致当前正在运行的线程睡眠(暂时性地停止运行)一段时间,不过这要受到系统定时器和调度器的精确度和准确性。调用Thread.sleep()方法的线程不会释放任何监视器上的锁,并且,该线程继续运行的时机要取决于运行该线程的处理器的调度和可用性。

有一点很重要,那就是不管是Thread.sleep()方法还是Thread.yield()方法都不没有任何同步语义。尤其是,在调用Thread.sleep()或Thread.yield()方法之前,编译器不必把写入到寄存器中的数据刷新到共享内存中。同时也不必在调用了Thread.sleep或Thread.yield()方法之后重新加载缓存在寄存器中的值。

代码


 例如,在下面的代码片中,假定this.done 是一个none volatile boolean 域字段(a non-volatile boolean field):

  while(!this.done){
     
     Thread.sleep(1000);
  }

  编译器只需要读取一次this.done域字段,并且在每次的循环中重复使用所缓存的值。这也就意味着 这个循环永远也不会结束,即使有另一个线程改变了this.done的值。


附上文档截图

13084796-ec5486cb94846b40.png
官方文档

我个人关于yield的说明

官方文档:

static void yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor.

yield操作就是放弃cpu的所有权。

“ yield the cpu to another thread of the same or lower priority ”

猜你喜欢

转载自blog.csdn.net/weixin_33733810/article/details/87119534