Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

java - Making a Thread to Sleep for 30 minutes

I want to make my thread to wait for 30 minutes. Are there any problems of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can make your thread sleep for 30 minutes like this:

Thread.sleep(30 *   // minutes to sleep
             60 *   // seconds to a minute
             1000); // milliseconds to a second

Using Thread.sleep is not inherently bad. Simply explained, it just tells the thread scheduler to preempt the thread. Thread.sleep is bad when it is incorrectly used.

  • Sleeping without releasing (shared) resources: If your thread is sleeping with an open database connection from a shared connection pool, or a large number of referenced objects in memory, other threads cannot use these resources. These resources are wasted as long as the thread sleeps.
  • Used to prevent race conditions: Sometimes you may be able to practically solve a race condition by introducing a sleep. But this is not a guaranteed way. Use a mutex. See Is there a Mutex in Java?
  • As a guaranteed timer: The sleep time of Thread.sleep is not guaranteed. It could return prematurely with an InterruptedException. Or it could oversleep.

    From documentation:

    public static void sleep(long millis) throws InterruptedException
    

    Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.


You could also use, as kozla13 has shown in their comment:

TimeUnit.MINUTES.sleep(30);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...