In a multi-threaded Java program, the entire program will not exit until all threads have completed execution. (It should be noted that execution of all non-daemon threads is completed; if a thread executes the System.exit() method, the program will also exit.) Sometimes, you want to abort the execution of a thread, for example, if you Want to exit the program, or you want to cancel a task being executed, etc.
Java provides an interrupt mechanism that allows us to explicitly interrupt the thread we want to terminate execution. One feature of the interrupt mechanism is that we can check whether the thread has been interrupted and then decide whether to respond to the abort request. The thread can also ignore the abort request and continue execution.
In this section, the sample program we developed will create a thread, and after five seconds, use the interrupt mechanism to forcefully terminate the thread.
know it
Follow the steps below to complete the sample program.
1. Create a class named PrimeGenerator and inherit the Thread class. The code is as follows:
Copy the code code as follows:
public class PrimeGenerator extends Thread {
2. Rewrite the run() method and add an infinite loop in the method. Within the loop, check whether the consecutive positive integers starting from 1 are prime numbers through calculation. If so, print to console. The code is as follows:
Copy the code code as follows:
@Override
public void run() {
long number = 1L;
while (true) {
if (isPrime(number)) {
System.out.printf("Number %d /tis Prime.", number);
}
3. After processing a number, check whether the thread was interrupted by calling the isInterrupted() method. If this method returns true, a sentence is printed to the console and then thread execution is terminated. The code is as follows:
Copy the code code as follows:
if (isInterrupted()) {
System.out.println("The Prime Generator has been Interrupted");
return;
}
number++;
}
}
4. Implement the isPrime() method, which is used to determine whether the parameter is a prime number. If so, it returns true, otherwise it returns false. The code is as follows:
Copy the code code as follows:
/**
* Determine whether the parameter is a prime number
*
* @param number The number to be judged
* @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:
Copy the code code 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:
Copy the code code as follows:
Thread task = new PrimeGenerator();
task.start();
7. Wait five seconds and then terminate the thread. The code is as follows:
Copy the code code as follows:
try {
TimeUnit.SECONDS.sleep(5L);
} catch (InterruptedException e) {
e.printStackTrace();
}
task.interrupt();
8. Run the example and view the results.
know why
Below is a printed snippet of the example program execution. From the printed characters, we can see how the PrimeGenerator thread prints out information and how to terminate its execution when it detects that the thread is interrupted.
Copy the code code as follows:
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 function to indicate whether the thread has been interrupted. When the interrupt() method is called, it is set to true. The isInterrupted() method returns the current value of the property.
never ending
Thread also has a method to check whether the thread is interrupted: the static method interrupted(), which can check whether the currently executing thread is interrupted.
Copy the code code as follows:
There is a big difference between the isInterrupted() method and the interrupted() method. The former will not change the property value of whether the thread is interrupted; while the latter can set its value to false. interrupted() is a static method; it is recommended to use the isInterrupted() method for daily development.
As mentioned earlier, a thread can ignore the interrupt request and continue execution. However, this is not the result we want.
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
A complete version of all the code used in the example program.
The complete code of the PrimeGenerator class is as follows:
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++;
}
}
/**
* Determine whether the parameter is a prime number
*
* @param number The number to be judged
* @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 of Main class
Copy the code code as follows:
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();
}
}