41 lines
1.3 KiB
Java
41 lines
1.3 KiB
Java
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");
|
||
}
|
||
}
|