add demo for interrupt

This commit is contained in:
Jason Lu 2025-03-02 21:22:12 +08:00
parent f6514d37a9
commit 59dbea0ecc

View File

@ -0,0 +1,40 @@
package threaddemo;
public class InterruptTest implements Runnable{
@Override
public void run() {
try {
while(true) {
boolean a = Thread.currentThread().isInterrupted();
System.out.println(STR."in run() - about to sleep for 20 seconds------- \{a}");
Thread.sleep(20000L);
}
} catch (InterruptedException e) {
//如果不加上这一句那么cd将会都是false因为在捕捉到InterruptedException异常的时候就会自动的中断标志置为了false
Thread.currentThread().interrupt();
boolean c = Thread.interrupted(); //true
boolean d = Thread.interrupted(); //false
System.out.println(STR."c = \{c}");
System.out.println(STR."d = \{d}");
}
}
public static void main(String[] args) {
InterruptTest it = new InterruptTest();
Thread t = new Thread(it);
t.start();
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("in main() - interrupting other thread");
//中断线程t
t.interrupt();
System.out.println("in main() - leaving");
}
}