Java concurrent programming example of five: thread sleep and recovery

  • 2020-04-01 03:33:15
  • OfStack

Sometimes, we need to interrupt the executing thread at a specified point in time. For example, once a minute the thread checks the state of the sensor, and the rest of the time the thread doesn't need to do anything. During this time, the thread does not need to use any of the computer's resources. After that time, and when the Java virtual machine schedules the thread, it continues to execute. To do this, you can use the sleeep() method of the Thread class. This method delays the execution of the thread by sleeping, and the integer type parameter indicates the number of milliseconds to sleep. When the sleep time ends by calling the sleep() method, the Java virtual machine assigns the thread's CPU time to run, and the thread resumes execution.

Another way to use the sleep() method is to enumerate the elements of the type TimeUnit. This method USES Thread's sleep() method to make the current Thread sleep, which takes the specified unit of time as an argument 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 every second.

learning

Follow the steps shown below to implement the sample in this section.

1. Create a class named FileClock and implement the Runnable interface. The code is as follows:


public class FileClock implements Runnable {

2. Implement the run() method. The code is as follows:

@Override
public void run() {

3. Write a loop that goes through ten times, creating a Date object in each iteration and printing it to the console. Then, the sleep() method is called through the TimeUtil SECONDS property to delay the execution of the thread by one second. Thought the sleep() method would throw InterruptedException. So, we need to write a few more lines of code to catch the exception. It is always best practice to release or close resources used in a thread when the thread may be interrupted. The code is as follows:

for (int i = 0; i < 10; i++) {
    System.out.printf("%sn", 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 implemented. Now, let's implement the main class. Create a class named FileMain and implement the main() method. The code is as follows:


public class FileMain {
    public static void main(String[] args) {

5. Create a FileClock object and a thread to execute the task. Then, start the thread. The code is as follows:


FileClock clock = new FileClock();
Thread thread = new Thread(clock);
thread.start();

In the main thread, the sleep() method is called through the TimeUtil SECONDS property to wait for five SECONDS. The code is as follows:

try {
    TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
    e.printStackTrace();
}

7. Interrupt the FileClock thread. The code is as follows:


thread.interrupt();

8. Execute the example to see how it works.

Know why

When you execute the program, you'll find out how the program prints the date object every second and how the thread is interrupted.

When the sleep() method is called, the thread leaves the CPU and stops executing for a while. During this time, the thread no longer needs the CPU, so the CPU can perform other tasks.

When a thread in hibernation is interrupted, it immediately throws an InterruptedException instead of waiting until the hibernation ends.

endless

There is another way in the Java concurrency API for threads to cede CPU. This is the yield() method, which is called to send a message to the Java virtual machine stating that the thread can cede the CPU to another thread. The Java virtual machine is not guaranteed to respond to this request. In general, this method is used only when debugging a program.

si

This article is a translation from the Java7 Concurrency Cookbook (D jago to Java7 Concurrency examples) and is intended for use only as a learning material. Not to be used in any commercial activities without authorization.

Small has becomes

A complete version of the sample code used in this section.

Complete code for the FileClock class


package com.diguage.books.concurrencycookbook.chapter1.recipe5; import java.util.Date;
import java.util.concurrent.TimeUnit; /**
 * Prints 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("%sn", new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                System.out.printf("The FileClock has been interrupted.n");
            }
        }
    }

The complete code for the FileMain class


package com.diguage.books.concurrencycookbook.chapter1.recipe5; import java.util.concurrent.TimeUnit; /**
 * Demonstrates thread sleep 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();
    }
}


Related articles: