简体   繁体   中英

Is Thread.sleep(1000); something reliable to use?

I know that Thread.sleep(1000); can be used to freeze the current thread (for 1 second in the example), but since you need to throw an Exception I am wondering if it is safe to use it. I don't want to use it in a program and accidentally cause problems.

Is it "ok" to use Thread.sleep(); or is there a better way to achieve the same outcome?

As an aside, if you want to sleep and know you won't be using interrupts, a handy way to avoid dealing with the InterruptedExceptions is using Guava's Uninterruptibles, eg

Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);

This transparently deals with the InterruptedException if one is thrown in the recommended way (ie resetting the interrupted status) and avoids unsightly try-catch blocks.

since you need to throw an Exception I am wondering if it is safe to use it.

Thread#sleep only throws 2 exceptions :

  • IllegalArgumentException if the parameter is negative
  • InterruptedException if the thread gets interrupted

=> if you pass a positive number and the thread doesn't get interrupted there will be no exception.

Unless you call theThread.interrupt() from another thread you will be fine.

EDIT

It seems you want to create a timer - in that case you would make your life much simpler by using the built-in mechanisms :

Runnable r = new Runnable() {
    public void run() { runYourTaskHere(); }
};
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(r, 0, 1, TimeUnit.SECONDS);

Depends on what you are trying to do, I have seen Thread.sleep used and it is usually used to fix a programming mistake, because people think it resolves race conditions. Thread.sleep has to throw an exception because Java doesn't control the CPU (last I checked), so if the CPU has a bug or even if it doesn't and wakes a thread up early / interrupts it in some way the program (Java) needs a way to terminate itself and propagate a message up the stack. Further this greatly depends on what you mean by "the same outcome"

It is perfectly safe. InterruptedException has been provided by JVM so that you can handle it if needed ( suppose you want to do something extra when this thread is interrupted)... It actually doesnt mean that something bad has happened.

Since thread.sleep Suspends the current thread for a specified time (not kill it). So it's safe to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM