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();
}

}

运行结果:

image

二、不清除打断标记

调用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();
}

}

运行结果

image

posted @ 2025-07-01 09:04  skystrivegao  阅读(60)  评论(0)    收藏  举报