add demo for interrupt
This commit is contained in:
parent
f6514d37a9
commit
59dbea0ecc
40
src/main/java/threaddemo/InterruptTest.java
Normal file
40
src/main/java/threaddemo/InterruptTest.java
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user