Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Thread sleep for random amount of MS

Tags:

Hey so I have 3 threads which have certain conditions when they print out something. this works fine. What I want to do now is make the thread just before it outputs something to send it to sleep for random amount of ms. I was thinking using the math class but not sure how.

the random() should generate random double greater than or equal to 0.0 and less than 1.0 right ?

will I just write something like

Thread.sleep(random()); 

^ that doesn't work though tried it

like image 886
Tom Avatar asked Nov 28 '12 20:11

Tom


People also ask

How do I make thread sleep for a minute?

To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);

Why thread sleep is not recommended?

If given a wait of 5000 Milliseconds(5 seconds) and an element just take just 1-2 seconds to load, script will still wait for another 3 seconds which is bad as it is unnecessarily increasing the execution time. So thread. sleep() increases the execution time in cases where elements are loaded in no due time.

How long should a thread sleep?

If it is a UI worker thread, as long as they have some kind of progress indicator, anywhere up to half a second should be good enough. The UI should be responsive during the operation since its a background thread and you definitely have enough CPU time available to check every 500 ms.

Is thread sleep in seconds or milliseconds?

sleep in Java. Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.


1 Answers

Thread.sleep() takes a long value not double. You would need a typecast here: -

Thread.sleep((long)(Math.random() * 1000)); 
like image 139
Rohit Jain Avatar answered Sep 20 '22 17:09

Rohit Jain