Sometimes, we need to interrupt the executing thread at a specified point in time. For example, a thread that checks the status of a sensor once every minute. The rest of the time, the thread does not need to do anything. During this time, the thread does not need to use any of the computer's resources. After this period of time has passed, and when the Java virtual machine schedules the thread, the thread continues to execute. To do this, you can use the sleep() method of the Thread class. This method delays the execution of the thread by sleeping, and the integer type parameter specifies the number of milliseconds to sleep. When the sleep() method is called and the sleep time is over, the Java virtual machine allocates CPU running time to the thread, and the thread will continue to execute.
Another way to use the sleep() method is through the elements of the enumeration type TimeUnit. This method uses Thread's sleep() method to make the current thread sleep. It can accept the specified unit of time as a parameter and convert it into the corresponding number of milliseconds.
In this section, we will develop a program that uses the sleep() method to print the current time every second.
know it
Follow the steps shown below to implement the examples in this section.
1. Create a class named FileClock and implement the Runnable interface. The code is as follows:
Copy the code code as follows:
public class FileClock implements Runnable {
2. Implement the run() method. The code is as follows:
Copy the code code as follows:
@Override
public void run() {
3. Write a loop that traverses ten times. In each iteration, create a Date object and print it to the console. Then, call the sleep() method through the SECONDS property of TimeUtil to delay the execution of the thread for one second. I thought the sleep() method would throw InterruptedException. Therefore, we need to write a few more lines of code to catch exceptions. When a thread may be interrupted, it is always best practice to release or close resources used in the thread. The code is as follows:
Copy the code code as follows:
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./n");
}
}
4. We already have a well-implemented thread class. Now, let's implement the main class. Create a class named FileMain and implement the main() method. The code is as follows:
Copy the code code as follows:
public class FileMain {
public static void main(String[] args) {
5. Create a FileClock object, and then create a thread to perform tasks. Then, start the thread. The code is as follows:
Copy the code code as follows:
FileClock clock = new FileClock();
Thread thread = new Thread(clock);
thread.start();
6. In the main thread, call the sleep() method through the SECONDS property of TimeUtil to wait for five seconds. The code is as follows:
Copy the code code as follows:
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
7. Interrupt the FileClock thread. The code is as follows:
Copy the code code as follows:
thread.interrupt();
8. Execute the example and check the execution effect.
know why
When you execute this program, you will find how the program prints the date object every second and how the thread is interrupted.
When the sleep() method is called, the thread will leave the CPU and stop execution for a period of time. During this time, the thread no longer needs the CPU, so the CPU can perform other tasks.
When a sleeping thread is interrupted, an InterruptedException will be thrown immediately instead of waiting until the sleep ends.
never ending
In the Java concurrency API, there is another method to allow threads to give up the CPU. This is the yield() method. Calling this method sends a message to the Java virtual machine indicating that the thread can give up the CPU to other threads. The Java virtual machine does not guarantee to respond to this request. Normally, this method is only used when debugging the program.
Use doctrine
This article is translated from "Java 7 Concurrency Cookbook" (D Gua Ge stole it as "Java7 Concurrency Example Collection") and is only used as learning materials. It may not be used for any commercial purposes without authorization.
Small success
The complete version of the sample code used in this section.
The complete code of the FileClock class is as follows:
package com.diguage.books.concurrencycookbook.chapter1.recipe5;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Print out the current date and time to the console every second.
* Date: 2013-09-18
* Time: 23:11
*/
public class FileClock implements Runnable {
@Override
public void run() {
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./n");
}
}
}
Complete code of FileMain class
Copy the code code as follows:
package com.diguage.books.concurrencycookbook.chapter1.recipe5;
import java.util.concurrent.TimeUnit;
/**
* Demo thread sleep and resume
* Date: 2013-09-19
* Time: 00:29
*/
public class FileMain {
public static void main(String[] args) {
FileClock clock = new FileClock();
Thread thread = new Thread(clock);
thread.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}