A multithreaded Java program, until all threads have finished executing, the entire program will not exit. (Note that all non-background threads (Non-daemon thread) are executed, and if a thread executes the System.exit () method, the program exits. Sometimes, you want to abort a thread's execution, such as if you want to quit the program, or you want to cancel a task that is being performed.
Java provides an interrupt mechanism that allows us to explicitly interrupt the thread we want to abort execution. One feature of the interrupt mechanism is that we can check whether the thread has been interrupted and 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 that, after five seconds, forces the thread to abort using the interrupt mechanism.
Know it
Complete the sample program as shown in the following steps.
1. Create a class named Primegenerator, and inherit the thread class. The code is as follows:
Copy Code code as follows:
public class Primegenerator extends Thread {
2. Rewrite the run () method to add an infinite loop to the method, within the loop, to check whether a contiguous positive integer starting at 1 is a prime number. If it is, it prints to the console. The code is as follows:
Copy 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 that the thread is interrupted by calling the Isinterrupted () method. If the method returns True, a word is printed to the console, and the thread execution is aborted. The code is as follows:
Copy 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 prime, returns true if it is, or returns false. The code is as follows:
Copy Code code as follows:
/**
* Determine if the parameter is a prime
*
* @param 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 implement the main () method at the same time. The code is as follows:
Copy 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 Code code as follows:
Thread task = new Primegenerator ();
Task.start ();
7. Wait five seconds, then abort the thread. The code is as follows:
Copy Code code as follows:
try {
TimeUnit.SECONDS.sleep (5L);
catch (Interruptedexception e) {
E.printstacktrace ();
}
Task.interrupt ();
8. Run the example to see the results.
Know the reason why
The following is a print fragment executed by the sample program. We can see from the printed characters how the primegenerator thread prints out the information and how to abort it when it detects that the thread is interrupted.
Copy 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 familiarity to indicate whether the threads are interrupted. When the interrupt () method is invoked, it is set 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: Static method Interrupted (), which can check whether the currently executing thread is interrupted.
Copy Code code as follows:
The isinterrupted () method and the interrupted () method are very different. The former does not change the value of the property to which the thread is interrupted, while the latter can set its value to false. Interrupted () is a static method, and it is recommended that the isinterrupted () method be used in normal development.
As mentioned earlier, a thread can continue executing without interrupting a request. But that's not the result we want.
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 all the code used by the sample program.
Complete code for the Primegenerator class
Copy Code code 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 if the parameter is a prime
*
* @param 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 for the main class
Copy 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 ();
}
}