Java-17.2 thread interruption (interrupt)
In this section, we will discuss thread interruption (interrupt ).
1. What is thread interruption (interrupt )?
When multiple threads are running, we add an interrupt mark to the thread, but the thread is not required to be terminated.
2. Example:
Example of Interruption:
package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintA printA = new PrintA();Thread threadA = new Thread(printA);threadA.start();}}class PrintA implements Runnable {private static int i = 0;@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println("PrintA");if (i == 2) {Thread.currentThread().interrupt();}i++;}}}
Output:
PrintA
PrintA
PrintA
Example without interruption:
package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintB printB = new PrintB();Thread threadB = new Thread(printB);threadB.start();}}class PrintB implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("PrintB");Thread.currentThread().interrupt();}}}
Output:
PrintB
PrintB
PrintB
PrintB
PrintB
From the two examples above, we can see that interrupt is only labeled with an interruption and will not force the interruption.
3. Conflict Between interrupt and sleep
Because when sleep is used after interrupt, sleep removes the interrupt mark.
Conflicting code, the following code will be output infinitely:
package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintA printA = new PrintA();Thread threadA = new Thread(printA);threadA.start();}}class PrintA implements Runnable {private static int i = 0;@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println("PrintA");if (i == 2) {Thread.currentThread().interrupt();try {Thread.currentThread().sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}i++;}}}
Summary: This section describes thread interruption (interrupt ).