java_multithread/src/main/java/threaddemo/InterruptTest.java
2025-03-02 21:22:12 +08:00

41 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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");
}
}