java多线程中的interrupt方法
时间: 2023-12-07 19:38:55 浏览: 37
在Java多线程中,interrupt()方法用于中断线程。但是需要注意的是,该方法并不会直接中止线程,而是通过某种方式通知线程,线程可以根据中断状态自行处理是否中止。下面是一个简单的例子:
```java
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread is running...");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread is interrupted!");
}
}
}, "t1");
t1.start();
Thread.sleep(5000);
t1.interrupt();
System.out.println("Thread is interrupted: " + t1.isInterrupted());
}
}
```
在上面的例子中,我们创建了一个线程t1,该线程会不断地输出"Thread is running...",且每隔1秒钟休眠一次。在主线程中,我们让程序休眠5秒钟后,调用t1的interrupt()方法中断线程。在t1的run()方法中,我们通过判断线程的中断状态来决定是否继续执行,如果线程被中断了,就会抛出InterruptedException异常,我们可以在catch块中处理中断事件。