java interrupt代码实例
时间: 2024-06-10 10:03:34 浏览: 18
在Java中,`interrupt()`方法是用于中断线程执行的一种机制,通常用于处理外部信号或用户交互请求。当一个线程调用另一个线程的`interrupt()`方法时,被中断线程会抛出`InterruptedException`异常。如果你想要演示一个简单的例子,你可以创建一个无限循环或者阻塞操作,然后检查是否被中断。
```java
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.TimeUnit;
public class InterruptExample {
private static final AtomicBoolean isInterrupted = new AtomicBoolean(false);
private Thread thread;
public static void main(String[] args) throws InterruptedException {
InterruptExample example = new InterruptExample();
example.thread = new Thread(() -> {
try {
System.out.println("Starting thread...");
// 模拟长时间运行的任务
while (!isInterrupted.get()) {
Thread.sleep(1000);
}
System.out.println("Thread interrupted.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
} finally {
System.out.println("Thread finishing.");
}
});
example.thread.start();
// 模拟外部中断请求
TimeUnit.SECONDS.sleep(2);
System.out.println("Interrupting thread...");
example.isInterrupted.set(true);
// 等待线程结束
example.thread.join();
}
}
```
在这个例子中:
1. `AtomicBoolean`用于控制线程是否被中断,初始值为`false`。
2. 主线程启动一个新的线程并让它进入一个无限循环,直到`isInterrupted`变为`true`。
3. 主线程等待一段时间后(这里模拟了2秒),调用`set(true)`中断线程。
4. 被中断的线程在循环中捕获到`InterruptedException`,并打印相关信息。
5. 最后,主线程通过`join()`方法等待线程完成(无论是否被中断)。