Java пауза time sleep

Метод sleep() класса java.lang.Thread используется для того, чтобы приостановить выполнение текущего потока на указанное в миллисекундах время. Значение аргумента для миллисекунд не может быть отрицательным, в противном случае будет брошен IllegalArgumentException .

Существует еще один способ приостановить выполнение работы программы: метод sleep(long millis, int nanos) . Он используется для того, чтобы приостановить выполнение текущего потока на точное время в миллисекундах и наносекундах. Значение наносекунд допустимо между 0 и 999999.

There are multiple ways to pause or stop the execution of currently running thread, but putting the thread into sleep state using Thread.sleep() method is the right way to introduce pause. Some people would say, why not use wait and notify?. Using those methods just for pausing thread is not good. Those are the tools for a conditional wait and they don’t depend on upon time. A thread blocked using wait() will remain to wait until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of wait() method is different, they are designed for inter-thread communication in Java. By using sleep() method, you pause the current for some given time. You should never use sleep() in place of wait() and notify() and vice-versa. There is another reason why to wait and notify should not be used to pause the thread, a they need lock. You can only call them from a synchronized method or block and acquire and release a lock is not cheap.

More importantly, why do you need to introduce lock just for pausing thread? Also one of the key difference between wait() and sleep() method is that, Thread.sleep() puts the current thread on wait but doesn’t release any lock it is holding, but wait does release the lock it holds before going into blocking state.

Читайте также:  Приложение для заучивания английских слов

In short, multi-threading is not easy, even a simple task like creating a thread, stopping a thread or pausing a thread require a good knowledge of Java API. You need to use the right method at the right place. If you are serious about mastering multi-threading and concurrency, I would suggest to read Java Concurrency in Practice twice and do every example given on that book. That book will change how you look a problem from multi-threading perspective.

How to pause Thread using Sleep in Java

Here is our sample Java program to pause a running thread using Thread.sleep() and TimeUnit.sleep() method in Java. In this simple program, we have two thread, main thread which is started by JVM and executes your Java program by invoking the public static void main(String args[]) method. The second thread is "T1" , which we have created and it is used to run our game loop. The Runnable task we passed to this thread has an infinite while loop, which runs until stopped. If you look at closely, we have used a volatile modifier to stop a thread in Java.

Main thread first starts the thread and then stops it by using stop() method in our Game >TimeUnit.sleep() method. So main thread can wait for some time and in the meantime, T1 will resume and finished. If you have not read already then you must read Java Concurrency in Practice to gain a comprehensive understanding of multithreading in Java.

In one example, we have learned two ways to pause a thread in Java, by using Thread.sleep() method and TimeUnit.sleep() method. The argument you pass to sleep() is time to sleep in a millisecond but that’s not clear from code. This is where TimeUnit class helps.

You get TimeUnit instance for a specific time unit e.g. TimeUnit.SECONDS or TimeUnit.MICROSECOND before calling sleep on it. You can see its much more clear how long a thread will wait now. In short, use TimeUnit class’ sleep() method to pause a thread because it’s more readable. To learn more about TimeUnit class, see my post why to prefer TimeUnit in Java.

Читайте также:  Цикл с переменной паскаль

Thread.sleep() and TimeUnit Example

Important points about sleep() method :

Now you know how to put a thread on sleep or pause, it’s time to know some technical details about Thread.sleep() method in Java.

1) Thread.sleep() is a static method and it always puts the current thread to sleep.

2) You can wake-up a sleeping thread by calling interrupt() method on the thread which is sleeping.

3) The sleep method doesn’t guarantee that the thread will sleep for exactly that many milliseconds, its accuracy depends on upon system timers and it’s possible for a thread to woke before.

4) It doesn’t release the lock it has acquired.

That’s all about how to put a thread on pause by using Thread.sleep() method and TimeUnit’s sleep() method. It’s better to use TimeUnit class because it improves readability of code, but its also not difficult to remember that argument passed to sleep() method is in millisecond. Two key things to remember is that Thread.sleep() is a static method and always put the current thread to sleep, and it doesn’t release any lock held by sleeping thread.

If you like this tutorial and interested in learning more about multi-threading in Java. You can also take a look at following Java multi-threading tutorials :

  • 10 things every Java programmer should know about Thread class (article)
  • What is the difference between Thread and Runnable in Java? (answer)
  • What is the difference between Process and Thread in Java? (answer)
  • Understanding the difference between wait() and sleep() in Thread? (answer)
  • What is the difference between Callable and Runnable in Java? (answer)
  • What is the difference between wait() and yield() method in Java? (answer)
  • When to use notify() and notifyAll() in Java? (answer)
  • What is the difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • The difference between yield() and sleep() method in Java? (answer)
Читайте также:  Горные лыжи wedze отзывы

Thanks for reading this article, if you like this tutorial then please share with your friends and colleagues.

I’m new to Java and making a small game for practice.

I want to pause the game for two seconds here before it does

How would I go about pausing it?

4 Answers 4

Please note that both of these methods throw InterruptedException , which is a checked Exception, So you will have to catch that or declare in the method.

Edit: After Catching the exception, your code will look like this:

Since you are new, I would recommend learning how to do exception handling once you are little bit comfortable with java.

You can find a similar post here: How to delay in Java?

Basically what says in the old post. You could use java.util.concurrent.TimeUnit

You can use Thread.currentThread().sleep(2000) to pause the current thread for 2 seconds (2000 milleseconds). You should surround this with a try/catch in case of InterruptedExceptions.

For those just wanting a quick hack without having to bring in a library.

For high precision 60fps gaming this probably isn’t what you want, but perhaps some could find it useful.

Not the answer you’re looking for? Browse other questions tagged java timer pause or ask your own question.



Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2019.11.15.35459

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock detector