interrupt():中断线程
isInterrupted():是否中断线程,如果是返回true,不是返回false
Thread.interrupted():是否中断线程,如果是返回true,不是返回false,不同于isInterrupted()的区别是,他会清除中断标记
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread() + "hello");
}
});
thread.start();
try {
Thread.sleep(1000);
System.out.println("main thread interrupt thread");
thread.interrupt();
thread.join();
System.out.println("main is over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 当现在还处在sleep方法的时候,调用interrupt 会抛出InterruptedException
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
System.out.println("threadOne begin sleep for 2000 seconds");
Thread.sleep(2000000);
System.out.println("threadOne awaking");
} catch (InterruptedException e) {
System.out.println("threadOne is interrupted while sleeping");
return;
}
System.out.println("thread-leaving normaily");
});
thread.start();
try {
// 确保子线程进入休眠状态
Thread.sleep(2000);
thread.interrupt();
thread.join();
System.out.println("main thread is over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 自旋
for (; ; ) {
}
});
// 启动线程
thread.start();
// 设置中断标志
thread.interrupt();
// 获取中断标志
System.out.println("isInterrupt:"+thread.isInterrupted());
// 获取中断标志并重置
System.out.println("isInterrupt:"+Thread.interrupted());
try {
// 程序一直不会停止
thread.join();
System.out.println("main thread is over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}