Java пауза в консоли

How to pause a Thread in Java? Thread.sleep and TimeUnit.sleep Example

There are multiple ways to pause or stop the execution of the currently running thread in Java, but putting the thread into a sleep state using the Thread.sleep() method is the right way to introduce a controlled pause. Some Java programmers would say, why not use the wait and notify? Using those methods just for pausing a thread is not a good coding practice in Java. Those are the tools for a conditional wait and they don’t depend on 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 the wait() method is different, they are designed for inter-thread communication in Java.

By using the 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 waiting and notify should not be used to pause the thread, they need a lock. You can only call them from a synchronized method or synchronized block and acquiring and releasing a lock is not cheap.

More importantly, why do you need to introduce lock just for pausing thread? Also one of the key differences between the 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.

Читайте также:  How to set font in html

In short, multi-threading is not easy, even a simple task like creating a thread, stopping a thread, or pausing a thread requires 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 joining a fundamental course for Java threads like Multithreading and Parallel Computing in Java from Udemy. It’s also very affordable and you can get in just $9.9 on Udemy sales.

How to pause a Thread using the Sleep method in Java?

Here is our sample Java program to pause a running thread using the Thread.sleep() and TimeUnit.sleep() method in Java. In this simple program, we have two threads, the 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 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 it closely, we have used a volatile modifier to stop a thread in Java.

The main thread first starts the thread and then stops it by using the stop() method in our Game class which extends Runnable.

When T1 starts it goes into a game loop and then pauses for 200 milliseconds. In between, we have also put the main thread to sleep by using TimeUnit.sleep() method.

So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution. If you want to learn more about Thread class and its essential methods then you can further see The Complete Java Masterclass, one of the best Java courses on Udemy to learn more about how to use the join method in Java.

Also, in just one example, we have learned two ways to pause a thread in Java, by using the Thread.sleep() method and the 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 like TimeUnit.SECONDS or TimeUnit.MICROSECOND before calling sleep on it. You can see it 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 on why to prefer TimeUnit in Java.

Thread.sleep() and TimeUnit Example

Here is a full code example to pause a thread in Java using Thread.sleep() or TimeUnit.sleep() method in Java:

import static java.lang.Thread.currentThread; import java.util.concurrent.TimeUnit; /** * Java Program to demonstrate how to pause a thread in Java. * There is no pause method, but there are multiple way to pause * a thread for short period of time. Two popular way is either * by using Thread.sleep() method or TimeUnit.sleep() method. * * @author java67 */ public class ThreadPauseDemo < public static void main(String args[]) throws InterruptedException < Game game = new Game(); Thread t1 = new Thread(game, "T1"); t1.start(); //Now, let's stop our Game thread System.out.println(currentThread().getName() + " is stopping game thread"); game.stop(); //Let's wait to see game thread stopped TimeUnit.MILLISECONDS.sleep(200); System.out.println(currentThread().getName() + " is finished now"); > > class Game implements Runnable< private volatile boolean isStopped = false; public void run() < while(!isStopped)< System.out.println("Game thread is running. "); System.out.println("Game thread is now going to pause"); try < Thread.sleep(200); > catch (InterruptedException e) < e.printStackTrace(); > System.out.println("Game thread is now resumed .."); > System.out.println("Game thread is stopped. "); > public void stop()< isStopped = true; > > Output main is stopping game thread Game thread is running..... Game thread is now going to pause Game thread is now resumed .. Game thread is stopped.... main is finished now

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 the Thread.sleep() method in Java.

1) The 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 the 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 system timers and it’s possible for a thread to wake before.

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

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

Other Java Concurrency Articles You may Like

  • The Complete Java Developer RoadMap ( roadmap )
  • 5 Courses to Learn Java Multithreading in-depth (courses)
  • When to use notify() and notifyAll() in Java? (answer)
  • 10 Java Multithreading and Concurrency Best Practices (article)
  • How to avoid deadlock in Java? (answer)
  • Understanding the flow of data and code in Java program (answer)
  • What is the difference between Callable and Runnable in Java? (answer)
  • How to do inter-thread communication in Java using wait-notify? (answer)
  • 10 Tips to become a better Java Developer (tips)
  • Difference between volatile, synchronized, and atomic (answer)
  • What is the difference between the wait() and yield() methods in Java? (answer)
  • Top 50 Multithreading and Concurrency Questions in Java (questions)
  • What is the difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • Top 5 Books to Master Concurrency in Java (books)
  • What is the difference between Thread and Runnable in Java? (answer)
  • Executor, Executors, and ExecutorService in Java (answer)
  • What is the difference between Process and Thread in Java? (answer)
  • ForkJoinPool and Executor Framework in Java(answer)
  • How to join two threads in Java? (answer)
  • What is Happens Before in Java Concurrency? (answer)
  • The difference between yield() and sleep() method in Java? (answer)

Thanks for reading this article so far. If you like this example of pausing a thread in Java and my explanation then please share it with your friends and colleagues. If you have any questions for feedback then please drop a comment.

P. S. — If you are just started with Java and want to master Threads in Java but looking for a free online training course to start with then I also, suggest you check out this awesome free Java Multithreading course on Udemy. This course is absolutely free and thousands of java developers have already joined this course.

Источник

Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we’ll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

The SleepMessages example uses sleep to print messages at four-second intervals:

public class SleepMessages < public static void main(String args[]) throws InterruptedException < String importantInfo[] = < "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" >; for (int i = 0; i < importantInfo.length; i++) < //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); >> >

Notice that main declares that it throws InterruptedException . This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn’t bother to catch InterruptedException .

Источник

Thread.sleep() in Java — Java Thread sleep

Thread.sleep() in Java - Java Thread sleep

The Java Thread.sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds. The argument value for milliseconds cannot be negative. Otherwise, it throws IllegalArgumentException .

sleep(long millis, int nanos) is another method that can be used to pause the execution of the current thread for a specified number of milliseconds and nanoseconds. The allowed nanosecond values are between 0 and 999999 .

In this article, you will learn about Java’s Thread.sleep() .

How Thread.sleep Works

Thread.sleep() interacts with the thread scheduler to put the current thread in a wait state for a specified period of time. Once the wait time is over, the thread state is changed to a runnable state and waits for the CPU for further execution. The actual time that the current thread sleeps depends on the thread scheduler that is part of the operating system.

Java Thread.sleep important points

  1. It always pauses the current thread execution.
  2. The actual time the thread sleeps before waking up and starting execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time, but for a busy system, it will be a little bit longer.
  3. Thread.sleep() doesn’t lose any monitors or lock the current thread it has acquired.
  4. Any other thread can interrupt the current thread in sleep, and in such cases InterruptedException is thrown.

Java Thread.sleep Example

Here is an example program where Thread.sleep() is used to pause the main thread execution for 2 seconds (2000 milliseconds):

package com.journaldev.threads; public class ThreadSleep  public static void main(String[] args) throws InterruptedException  long start = System.currentTimeMillis(); Thread.sleep(2000); System.out.println("Sleep time in ms = " + (System.currentTimeMillis() - start)); > > 

First, this code stores the current system time in milliseconds. Then it sleeps for 2000 milliseconds. Finally, this code prints out the new current system time minus the previous current system time:

Output
Sleep time in ms = 2005

Notice that this difference is not precisely 2000 milliseconds. This is due to how Thread.sleep() works and the operating system-specific implementation of the thread scheduler.

Conclusion

In this article, you learned about Java’s Thread.sleep() .

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью