blog
blog copied to clipboard
线程的中断
trafficstars
Java 线程中断
Java 的 Thread 提供了三个方法:
// 设置线程中断状态
public void interrupt()
// 判断线程是否中断
public boolean isInterrupted()
// 判断当前线程是否中断(静态方法)
public static boolean interrupted()
关于线程中断,Java 提供了通过“中断状态”来让线程自己处理相应的中断业务逻辑,代码如下:
public class TestInterrupt {
static void getAppleList() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) {
// Track interrupt signal
throw new InterruptedException("Thread Interrupt.");
}
// 模拟耗时长的业务操作
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
list.add("apple" + i);
}
System.out.println(list);
}
static class MyThread extends Thread {
@Override
public void run() {
try {
getAppleList();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
thread.interrupt();
}
}
如上代码,我们设置线程中断状态,在线程的业务逻辑中捕获中断状态,后续可以对其做相关的业务操作来保证对象的完整性。
同步阻塞状态下的中断
如果线程在执行同步的 Socket I/O 或者在获取锁的过程中发生了阻塞,那么中断请求只能设置中断状态。但是程序中的中断操作并不会被执行。
这时候需要改写 Thread.interrupt() 方法,把所有的处理放在 interrupt() 方法中:如关闭 Socket、关闭 Http 链接。