问题描述
这里是我在一些我正在维护的代码中看到的代码片段。
Object lock = new Object ;
synchronized(lock)
{
try
{
lock.wait(50000);
Thread.sleep(3000);
}
catch(例外)
{
}
}
开发者想要暂停当前线程一段时间,并使用Object#wait作为机制。显然,由于这个原因,使用wait / notify协议是不好的;但是,调用wait(毫秒)和Thread.sleep之间有什么主要区别吗?
除了在等待之前得到一个监视器()之外,没有任何外部的在古Java代码中,你会看到人们使用wait()而不是Thread.sleep(),因为Thread.sleep()会冻结整个应用程序在系统上没有抢先的多任务(我在看你OS9)。技术上wait()也让你使用纳米分辨率等待,但在实践中,它们很少准确。
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 );
Thread.sleep( 3000 );
}
catch(Exception ex)
{
}
}
The developer wants to suspend the current thread for some amount of time and is using Object#wait as the mechanism. Obviously it is bad form to use the wait/notify protocol for this reason; however, is there any major difference between calling wait(millisec) and a Thread.sleep ?
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.
这篇关于使用Object.wait(毫秒)来模拟睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!