Java thread interruption
Interrupt () function can be used to interrupt threads in java. Although this function cannot terminate the running of the thread, it can change the thread status to true.
That is, the isInterrupted () value is returned as true.
Note: When a function calls a blocked thread, the blocked thread will receive an InterruptedException exception. That is, the current thread can be terminated.
For example:
Package TestThread. threadSynchronized; public class TestWaitAll {public static void main (String [] args) {// create a thread object Test1 test1 = new Test1 (); // create Thread t = new Thread (test1, "Thread 1"); Thread t1 = new Thread (test1, "Thread 2"); Thread t2 = new Thread (test1, "Thread 3"); Thread t3 = new Thread (test1, "Thread 4"); // This is the wake-up Thread Test2 test2 = new Test2 (test1, "Wake-Up Thread "); t. start (); t1.start (); t2.start (); t2.interrupt (); // interrupt thread t3.sta Rt (); try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace () ;}// start the wake-up thread test2.start () ;}} class Test1 implements Runnable {public void run () {synchronized (this) {// when the blocked thread calls interrupt, an exception will occur. try {this. wait (); System. out. println (Thread. currentThread (). getName () + ": I have not been interrupted. I can execute it! ");} Catch (InterruptedException e) {System. out. println (Thread. currentThread (). getName () +": interrupted! ");}}}} /*** @ Author CHAI015 generates a wake-up class */class Test2 extends Thread {/*** Test1 indicates that the name of the wake-up object is the Thread name */private Test1 test1; String name; /*** @ param test1 wake-up object * @ param name wake-up name */public Test2 (Test1 test1, String name) {super (name); this. name = name; this. test1 = test1;} public void run () {synchronized (test1) {test1.policyall (); // executes the System action to wake up all threads for the current object. out. println (Thread. currentThread (). getName () + ": Wake up thread execution Successful! ");}}}
The running result is: