Sometimes we need to interrupt an executing thread at a specified point in time. For example, the thread that checks the sensor state every minute, and 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 time, and when the Java Virtual machine dispatches the thread, the thread continues to execute. To do this, you can use the Sleeep () method of the thread class. The method defers the execution of the thread in a dormant manner, and the parameter of the integer type indicates the number of milliseconds to sleep. When the sleep () method is invoked and the Java Virtual machine is assigned to the thread CPU run time after the hibernation time is over, the thread continues to execute.
The other way is to use the sleep () method to timeunit elements by enumerating the types. This approach uses the thread's sleep () method to hibernate the current thread, which can accept the time of the specified unit as a parameter and converts it to the corresponding number of milliseconds.
In this section, we'll develop a program that uses the sleep () method to print the current time per second.
Know it
Follow the steps below to implement the example in this section.
1. Create a class named Fileclock and implement the Runnable interface. The code is as follows:
Copy Code code as follows:
public class Fileclock implements Runnable {
2. Implement the Run () method. The code is as follows:
Copy Code code as follows:
@Override
public void Run () {
3. Write a loop that traverses 10 times, in each iteration, create a Date object and print it to the console. The sleep () method is then invoked through the Timeutil seconds property to delay the execution of the thread by one second. Think the sleep () method throws a Interruptedexception exception. So, we need to write a few more lines of code to catch the exception. When a thread is likely to break, it is always best practice to release or shut down resources used in threads. The code is as follows:
Copy Code code as follows:
for (int i = 0; i < 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 good thread class to implement. Now we're going to implement the main class. Create a class named Filemain, and implement the main () method. The code is as follows:
Copy 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 the task. Then, start the thread. The code is as follows:
Copy Code code as follows:
Fileclock Clock = new Fileclock ();
Thread thread = new thread (clock);
Thread.Start ();
6. In the main thread, wait five seconds by calling the sleep () method through the Timeutil seconds property. The code is as follows:
Copy Code code as follows:
try {
TimeUnit.SECONDS.sleep (5);
catch (Interruptedexception e) {
E.printstacktrace ();
}
7. Interrupt Fileclock Thread. The code is as follows:
Copy Code code as follows:
8. Perform the example to see the execution effect.
Know the reason why
When you execute this program, you will find out how the program prints a Date object every second, and when the thread is interrupted.
When the sleep () method is invoked, the thread leaves the CPU and stops execution for a period of time. During this time, the thread does not need the CPU, so the CPU can perform other tasks.
When a thread in hibernation is interrupted, a interruptedexception is thrown immediately, rather than waiting until the hibernation is over.
Endless
In the Java Concurrency API, there is another way to let a thread out of the CPU. This is the yield () method, which calls the Java Virtual machine to send a message stating that the thread can relinquish the CPU to another thread. Java virtual machines are not guaranteed to respond to this request. In general, this method is only used when debugging a program.
Copycat
This article is from the "Java 7 Concurrency Cookbook" (D-Gua to "Java7 concurrent Sample Set") translation, only as learning materials used. No authorization shall be applied to any commercial act.
Small has become
The full version of the sample code used in this section.
Complete code for the Fileclock class
Copy Code code as follows:
Package com.diguage.books.concurrencycookbook.chapter1.recipe5;
Import Java.util.Date;
Import Java.util.concurrent.TimeUnit;
/**
* Print the current date and time to the console per second.
* date:2013-09-18
* Time:23:11
*/
public class Fileclock implements Runnable {
@Override
public void Run () {
for (int i = 0; i < 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 for the Filemain class
Copy Code code as follows:
Package com.diguage.books.concurrencycookbook.chapter1.recipe5;
Import Java.util.concurrent.TimeUnit;
/**
* Demo thread hibernation and recovery
* 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 ();
}
}