Using Object.wait(millisec) to simulate sleep

后端 未结 3 1385
庸人自扰
庸人自扰 2021-01-06 02:15

Here\'s a snippet of code that I saw in some code I\'m maintaining.

Object lock = new Object();

synchronized( lock ) 
{
   try
   {
       lock.wait( 50000          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-06 02:49

    Aside from having to get a monitor before waiting() there's no major difference anymore so long as no one external is going to be .notify()ing.

    In ancient Java code you'd see people using wait() instead of Thread.sleep() because Thread.sleep() would freeze the whole application on systems without preemptive multitasking (I'm looking at you OS9). Technically wait() also let's you use nano-resolution waits, but in practice they're seldom that accurate.

提交回复
热议问题