Thread.interrupted() 可以返回当前标志位并使标志位为false
Thread.currentThread().interrupt() 可以使标志位置为true
Thread.currentThread().isInterrupted() 返回当前线程标志位
如果线程中使用了sleep,wait,当调用thread.interrupt()的时候,会使当前线程中断标志位值为false,
并触发异常InterruptedException
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(0);
Thread thread = new Thread(() -> {
for (; ; ) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("InterruptedException "+Thread.currentThread().isInterrupted());
boolean interrupted = Thread.interrupted();
System.out.println("interrupted===="+interrupted);
}
int i = atomicInteger.incrementAndGet();
if (i==2){
Thread.currentThread().interrupt();
// boolean interrupted = Thread.interrupted();
// System.out.println("interrupted===="+interrupted);
}
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread.currentThread().isInterrupted() "+Thread.currentThread().isInterrupted());
if (i==80000){
boolean interrupted = Thread.interrupted();
System.out.println("interrupted===="+interrupted);
}
// boolean interrupted = Thread.interrupted();
// System.out.println("interrupted===="+interrupted);
}
System.out.println(Thread.currentThread().isInterrupted());
// if (Thread.currentThread().isInterrupted()) {
// System.out.println(Thread.currentThread().isInterrupted());
// }
}
});
thread.start();
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("Interrupted");
// Thread.interrupted();
// thread.interrupt();
// thread.in
}