How to make another thread sleep in Java

You can’t make another thread sleep. (You can use the deprecated suspend() method, but please don’t). This call:

this.sleep(200);

will actually make the currently executing thread sleep – not the Thread referred to by “this”. sleep is a static method – good IDEs will issue a warning over that line.

You should just have a flag saying “sleep please” and then make the sleeper thread check that flag before doing any work.

It’s a good thing that you can’t cause another thread to sleep. Suppose it’s in a synchronized method – that would mean you’d be holding a lock while sleeping, causing everyone else trying to acquire the same lock to block. Not a good thing. By using a flag-based system, you get to sleep in a controlled way – at a point where you know it’s going to do no harm.

Leave a Comment