什么叫中断
中断是指计算机运行过程中,出现某些意外情况需主机干预时,机器能自动停止正在运行的程序并转入处理新情况的程序,处理完毕后又返回原被暂停的程序继续运行。
java的中断
中断在java中主要有3个方法:
1.interrupt():
(1)在一个线程中调用另一个线程的interrupt()方法,即会向那个线程发出信号,线程中断状态已被设置;
(2)至于那个线程何去何从,由具体的代码实现决定(interrupt()不能中断在运行中的线程,它只能改变中断状态而已;没有任何语言方面的需求要求一个被中断的程序应该终止。中断一个线程只是为了引起该线程的注意,被中断线程可以决定如何应对中断)
2.isInterrupted():获取当前线程的中断状态(true or false),不会重置中断状态。
3.interrupted():获取当前线程的中断状态(true or false),会重置中断状态。
示例1(interrupt不能中断线程执行)
package interrupted;
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {
while(true) {
System.out.println("I'm running...");
}
}
});
t.start();
t.interrupt();
}
}
结果:调用interrupt后,线程并没有被中断,控制台仍在在输出。

示例2(interrupt经典使用方式):
package interrupted;
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted()) {
System.out.println("I'm running...");
}
}
});
t.start();
Thread.sleep(2000);
t.interrupt();
}
}
结果:调用interrupt后,控制台不再输出,说明线程已经被中断。

示例3(用InterruptException处理阻塞状态):
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread r = new Thread(new TestRunnable());
r.start();
Thread.sleep(1000);
r.interrupt();
}
}
public class TestRunnable implements Runnable {
public void run() {
try {
System.out.println("I'm sleeping...");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("I'm interrupted");
}
}
}
结果:

分析:当线程被阻塞时(Object.wait, Thread.sleep, Thread.join),调用它的interrupt方法时,没有占用CPU运行的线程是不可能给自己的中断状态置位的,这就会产生一个InterruptedException异常。
参考资料:java 线程 interrupted_java线程之中断线程Interrupted用法
本文介绍了中断在计算机编程,特别是Java中的概念,包括interrupt(),isInterrupted(),interrupted()方法的使用,以及中断如何影响线程执行和处理阻塞情况。通过示例展示了中断操作的实际效果和可能遇到的InterruptedException异常。
1万+

被折叠的 条评论
为什么被折叠?



