Using Object.wait(millisec) to simulate sleep

后端 未结 3 1475
庸人自扰
庸人自扰 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:54

    You say it's "obviously" bad form to use wait/notify for this, but I don't see anything wrong with it. Admittedly following it up with a sleep call is very odd (and swallowing exceptions is bad), but I've definitely used Object.wait as a "breakable sleep" before now.

    Imagine you've got a thread polling a resource every minute, but you want to be woken if something's happened (e.g. the resource location has changed, or the timer frequency has changed, or the program wants to quit in a graceful manner). Using wait/notify works extremely well for that - it's definitely cleaner than calling interrupt on the thread from elsewhere, as it doesn't matter if the notify occurs while you're actually processing instead of waiting.

提交回复
热议问题