Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Is Thread.sleep() synchronised method ?  RSS feed

 
Atul Prabhu
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



I create two thread instances of ThreadTest and call the start method of the thread.

In this case whether the Thread.sleep() is synchronised or not ?
Does the user has to handle the synchronised part ?

Regards
Atul
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, sleep() is not a synchronized method, and has no special synchronization concerns -- other than the fact that calling sleep() while holding the lock of any object may be a bad idea.
 
Atul Prabhu
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks Ernest Friedman-Hill.

If one wants that the current thread to sleep() what should be done without acquiring the lock on the shared object ?

would a call to function which just iterates the "for" loop be sufficient ?
i.e for(int i =0 ; i <1000; i++) {}

or is there anything else which I am not aware of.

Regards
Atul
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using loops to implement time delays went out with BASIC. It is a bad idea because the amount of time delay may vary hugely depending on processor power, loading and also on the extent to which compiler and/or hotspot are able to optimise-away redundant code like an empty loop.

Use Thread.sleep() or Thread.wait(). The former does not require you to hold the lock on "this" and indeed you generally should not hold any locks when doing sleep(). The latter does require you to hold the lock on "this", but releases it while wait()ing, then regains it when finished waiting.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:


Use Thread.sleep() or Thread.wait(). The former does not require you to hold the lock on "this" and indeed you generally should not hold any locks when doing sleep(). The latter does require you to hold the lock on "this", but releases it while wait()ing, then regains it when finished waiting.


wait() a an instance method of Object (not only Thread). ("this" is the object used to call wait().)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!