Sleeping and resuming a thread
Sometimes, you may be interested in pausing the execution of a thread during a determined period of time. For example, a thread in a program checks the sensor state once per minute. The rest of the time, it does nothing. During this time, the thread doesn't use any resources of the computer. After this period is over, the thread will be ready to continue with its execution when the operating system scheduler chooses it to be executed. You can use the sleep()
method of the Thread
class for this purpose. This method receives a long number as a parameter that indicates the number of milliseconds during which the thread will suspend its execution. After that time, the thread continues with its execution in the next instruction to the sleep()
one when the JVM assigns it CPU time.
Another possibility is to use the sleep()
method of an element of the TimeUnit
enumeration. This method uses the sleep()
method of the Thread
class to put the current thread to sleep, but it receives the parameter in the unit that it represents and converts it into milliseconds.
In this recipe, we will develop a program that uses the sleep()
method to write the actual date every second.
Getting ready
The example for this recipe has been implemented using the Eclipse IDE. If you use Eclipse or a different IDE, such as NetBeans, open it and create a new Java project.
How to do it...
Follow these steps to implement the example:
- Create a class called
ConsoleClock
and specify that it implements theRunnable
interface:
public class ConsoleClock implements Runnable {
- Implement the
run()
method:
@Override public void run() {
- Write a loop with 10 iterations. In each iteration, create a
Date
object, write it to the console, and call thesleep()
method of theSECONDS
attribute of theTimeUnit
class to suspend the execution of the thread for 1 second. With this value, the thread will be sleeping for approximately 1 second. As thesleep()
method can throw anInterruptedException
exception, we have to include some code to catch it. It's good practice to include code that frees or closes the resources the thread is using when it's interrupted:
for (int i = 0; i < 10; i++) { System.out.printf("%s\n", new Date()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.out.printf("The FileClock has been interrupted"); } } }
- We have implemented the thread. Now let's implement the main class of the example. Create a class called
Main
that contains themain()
method:
public class Main { public static void main(String[] args) {
- Create an object of the
FileClock
class and athread
to execute it. Then, start executing a thread:
FileClock clock=new FileClock(); Thread thread=new Thread(clock); thread.start();
- Call the
sleep()
method of theSECONDS
attribute of theTimeUnit
class in the main thread to wait for 5 seconds:
try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); };
- Interrupt the
FileClock
thread:
thread.interrupt();
- Run the example and see the results.
How it works...
When you run the example, you would see how the program writes a Date
object per second and also the message indicating that the FileClock
thread has been interrupted.
When you call the sleep()
method, the thread leaves the CPU and stops its execution for a period of time. During this time, it's not consuming CPU time, so the CPU could be executing other tasks.
When the thread is sleeping and is interrupted, the method throws an InterruptedException
exception immediately and doesn't wait until the sleeping time is finished.
There's more...
The Java concurrency API has another method that makes a thread object leave the CPU. It's the yield()
method, which indicates to the JVM that the thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it's only used for debugging purposes.