public class SleepInterrupt extends Object implements Runnable { @Override public void run() { System.out.println("in run() - enter normally"); try { System.out.println("in run() - about to sleep for 20 seconds"); Thread.sleep(20000); System.out.println("in run() - woke up"); } catch (InterruptedException e) { System.out.println("in run() - interrupted while sleeping"); /** * After processing the interrupt exception, return to the entry of the run() method, * If there is no return, the thread will not actually be interrupted, it will continue to print the following information */ return; } System.out.println("in run() - leaving normally"); } }
public class InterruptDemo { public static void main(String[] args) { SleepInterrupt sleepInterrupt = new SleepInterrupt(); Thread thread = new Thread(sleepInterrupt); thread.start(); // The main thread sleeps for 2 seconds to ensure that the thread just started has a chance to execute for a while try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("in main() - interrupting other thread"); /** * When a thread is running, another thread can call the interrupt() method of the corresponding Thread object to interrupt it, * This method just sets a flag in the target thread, indicating that it has been interrupted, and returns immediately */ thread.interrupt(); System.out.println("in main() - leaving"); } }