'How to use Thread.sleep for only one function in Java?
When using Thread.sleep and TimeUnit, the entire application is paused, but I need the pause to be only inside the function, that is:
while (i<100) {
i++;
"Sleep one second"
System.out.println(i);
}
There is an example?
Solution 1:[1]
Background thread
Use the executors framework in Java to launch your lengthy task in a background thread. When that task blocks, the original main thread will still be continuing to run without pause.
Define your task as a Runnable or Callable. You can do this as a separate class, a named nested class, an anonymous class, or as a lambda. Here is an example of the lambda approach.
Runnable task = () -> { // lambda expression
int i = 0 ;
while ( i < 100 ) {
i++;
try { Thread.sleep( 1_000 ); } catch ( InterruptedException e ) { System.out.println( e ); } // Sleep to simulate a workload that takes some time.
System.out.println( i );
}
};
In real code you would check for interruption state, and bail out of the for loop, if appropriate. Ditto for responding to an InterruptedException.
Instantiate an executor service by using the Executors utility class. Likely a single-threaded executor will be suitable to your case.
Submit an instance of your task to the executor service.
Keep a reference to the executor service if your app might be able to reuse it.
Before your app exits, be sure to gracefully shutdown your executor service. Otherwise its backing pool of threads may continue running indefinitely, like a zombie ????. See Javadoc for full example code.
All this has been covered many times already on Stack Overflow. Search for ExecutorService and Executors classes to learn more.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
