JUC学习-10-打断线程
JUC学习-10-打断线程
# 判断当前线程是否被打断,清除打断标记
pubilc static boolean interrupted()
# 判断当前线程是否被打断,不清除打断标记
public boolean isInterrupted()
一、静态打断方法 并且清除打断标记
可以看到,虽然在sleep方法后调用了interrupted()打断方法,但是并没有抛出异常。
class TestInterrupted {
static Thread t1 = new Thread() {
@Override
public void run() {
try {
System.out.println(Thread.interrupted() + "");
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
public static void main(String[] args) {
t1.start();
t1.interrupt();
}
}
运行结果:
二、不清除打断标记
调用sleep()方法后再调用isInterrupted()方法,此时会抛出异常:java.lang.InterruptedException: sleep interrupted
class TestInterrupted {
static Thread t1 = new Thread() {
@Override
public void run() {
try {
// System.out.println(Thread.interrupted() + "");
// 不清除打断标记
System.out.println(currentThread().isInterrupted());
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("线程睡眠结束");
}
};
public static void main(String[] args) {
t1.start();
t1.interrupt();
}
}
运行结果
本文来自博客园,作者:skystrivegao,转载请注明原文链接:https://www.cnblogs.com/skystrive/p/18959054
整理不易,如果对您有所帮助 请点赞收藏,谢谢~