Of 3: thread interruption

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

A multithreaded Java program that does not exit until all threads have finished executing. (note that all non-daemon threads execute; If a thread executes the system.exit () method, the program exits. Sometimes, you want to abort the execution of a thread, such as you want to exit the program, or you want to cancel an ongoing task.

Java provides an interrupt mechanism that allows us to explicitly interrupt the thread we want to abort. One feature of the interrupt mechanism is that we can check whether the thread has been interrupted and then decide whether to respond to an abort request. The thread can also ignore the abort request and continue execution.

In this section, we develop a sample program that creates a thread and, after five seconds, USES an interrupt mechanism to force the thread to stop.

learning

Complete the sample program as shown in the following steps.

1. Create a class called PrimeGenerator and inherit from the Thread class. The code is as follows:


public class PrimeGenerator extends Thread {

2. Override the run() method to add an infinite loop to the method, in which the successive positive integers starting at 1 are evaluated to see if they are prime. If so, print to the console. The code is as follows:

@Override
public void run() {
    long number = 1L;
    while (true) {
        if (isPrime(number)) {
            System.out.printf("Number %d tis Prime.", number);
        }

After processing a number, check if the thread has been interrupted by calling the isInterrupted() method. If this method returns true, it prints a sentence to the console, and then aborts the thread execution. The code is as follows:

        if (isInterrupted()) {
            System.out.println("The Prime Generator has been Interrupted");
            return;
        }         number++;
    }
}

4. Implement the isPrime() method, which determines whether the parameter isPrime, and returns true if it is, or false if it is not. The code is as follows:


/**
 * Determines whether the parameter is prime
 *
 * @param number Numbers to judge
 * @return
 */
private boolean isPrime(long number) {
    if (number <= 2) {
        return true;
    }     for (int i = 2; i < number; i++) {
        if ((number % i) == 0) {
            return false;
        }
    }     return true;
}

5. Now, implement the Main class of the sample program, the Main class, and the Main () method. The code is as follows:

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

6. Create a PrimeGenerator object and start the thread. The code is as follows:

Thread task = new PrimeGenerator();
task.start();

7. Wait five seconds, then abort the thread. The code is as follows:

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

8. Run the example to see the results.

Know why

The following is a printed snippet of the execution of the sample program. The printed characters show how the PrimeGenerator thread prints out information and aborts execution when it detects that the thread is interrupted.


Number 43063    is Prime.
Number 43067    is Prime.
Number 43093    is Prime.
Number 43103    is Prime.
Number 43117    is Prime.
The Prime Generator has been Interrupted

Thread has a Boolean familiarity to indicate whether the Thread is interrupted. When you call the interrupt() method, you set it to true. The isInterrupted() method returns the current value of the property.

endless

Thread also has a way to check if a Thread is interrupted: the static method interrupted() checks if the currently executing Thread is interrupted.


isInterrupted() Methods and interrupted() The methods are very different. The former does not change the property value of whether the thread is interrupted or not; The latter can be set to false . interrupted() It's a static method; Development is recommended isInterrupted() Methods.

As mentioned earlier, threads can ignore interrupt requests and continue execution. However, this is not the result we want.

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 all the code used in the sample program.

Full code for the PrimeGenerator class


package com.diguage.books.concurrencycookbook.chapter1.recipe3; /**
 * Date: 2013-09-18
 * Time: 11:53
 */
public class PrimeGenerator extends Thread {     @Override
    public void run() {
        long number = 1L;
        while (true) {
            if (isPrime(number)) {
                System.out.printf("Number %d tis Prime.n", number);
            }             if (isInterrupted()) {
                System.out.println("The Prime Generator has been Interrupted");
                return;
            }             number++;
        }
    }     /**
     * Determines whether the parameter is prime
     *
     * @param number Numbers to judge
     * @return
     */
    private boolean isPrime(long number) {
        if (number <= 2) {
            return true;
        }         for (int i = 2; i < number; i++) {
            if ((number % i) == 0) {
                return false;
            }
        }         return true;
    }
}

The complete code for the Main class


package com.diguage.books.concurrencycookbook.chapter1.recipe3; import java.util.concurrent.TimeUnit; /**
 * Date: 2013-09-18
 * Time: 12:33
 */
public class Main {
    public static void main(String[] args) {
        Thread task = new PrimeGenerator();
        task.start();         try {
            TimeUnit.SECONDS.sleep(5L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }         task.interrupt();
    }
}


Related articles: