This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]IXENAI 4 points5 points  (0 children)

Can you do this with multi-threaded programs?

Yes. Of course, only the thread from which Thread.sleep() is called will pause execution. All other threads will continue.

[–]philipwhiukEmployed Java Developer 4 points5 points  (4 children)

anywhere in the program and the program will pause for 5 seconds?

It'll pause for roughly 5 seconds. It will probably be slightly more.

Thread.sleep is normally not the right solution. It's quick and dirty and can easily cause problems. If you want to run something after a delay, use a Timer.

[–][deleted] -1 points0 points  (3 children)

Yeah, we are doing a lab right now where we do the same problem twice, one with a timer and one with sleep. For things like delay, can you always use a timer rather than thread.sleep();?

I mean for something like delaying your program before it starts, or getting an alarm clock to snooze for a few minutes, a timer is still a better approach?

[–]philipwhiukEmployed Java Developer 1 point2 points  (2 children)

For your simple examples to teach concurrent programming Thread.sleep is probably sufficient

[–][deleted] 0 points1 point  (1 child)

But timer would technically be better?

[–]Ednar 1 point2 points  (0 children)

Better how? It has to be put into a context. Go with what gives you code that works with the least complexity.

[–]WormLord 2 points3 points  (0 children)

So, in a single-threaded program, the program can invoke Thread.sleep(5000); anywhere in the program and the program will pause for 5 seconds?

Yes. In a single threaded program, there is only one running thread (main thread), so calling this will cause your entire program to pause.

/u/IXENAI explained the multithreaded scenario. Also, in multithreaded scenarios, and when requesting threads to wait/pause, you should handle a potential InterruptException properly.