您现在的位置是:亿华云 > IT科技类资讯

聊聊 Java 中的中断机制

亿华云2025-10-09 13:06:01【IT科技类资讯】1人已围观

简介在Java中,用于终止一个正在运行中的线程,并非调用stop方法,而是自行设置一个标志位,在安全点检测标志位,决定是否退出,但也可能会因为线程被挂起,无法走到标志位。因此,Java线程提供了中断机制,

在Java中,聊聊用于终止一个正在运行中的中的中断线程,并非调用stop方法,机制而是聊聊自行设置一个标志位,在安全点检测标志位,中的中断决定是机制否退出,但也可能会因为线程被挂起,聊聊无法走到标志位。中的中断因此,机制Java线程提供了中断机制,聊聊Thread类提供了中断线程执行的中的中断调用方法:interrupt,用于中断因线程挂起的机制等待,调用interrupt方法后,聊聊线程会被唤醒,中的中断待下次cpu调度就会继续执行中断后的机制代码 。

我们经常会调用Thread#sleep、Object#wait、Queue#poll等方法,并要求我们处理InterruptedException异常。 那么,抛出InterruptedException后,线程会终止吗?

如果不捕获InterruptedException,那么线程就会因为异常终止,源码库是因为异常终止,并不是因为被中断。如果捕获了InterruptedException,那么线程就不会终止。

中断,其实只是jvm用于唤醒因锁竞争、I/O操作、休眠等待被挂起的线程,并设置一个中断标志,我们可以利用这个标志去做一些处理。比如,当我们发送消息给远程服务器,并休眠等待结果时,如果线程被唤醒,并设置了中断标志,此时我们可以知道,并非等到结果被唤醒的,而是被中断唤醒的,可以决定是继续等待结果,还是放弃等待。

xxl-job提供取消任务操作,而任何运行中的线程,都只能利用中断机制去结束线程任务,服务器托管所以我们想要任务支持被取消,那么在写定时任务时,一定要考虑清楚,是不是应该捕获InterruptedException,如何利用中断标志结束任务,否则将会导致任务无法被取消。

我们来看个案例:

@Test public void test() {      ExecutorService executorService = Executors.newSingleThreadExecutor();     Future<?> future = executorService.submit(() -> {          while (true) {              System.out.println( "rung....." );             ThreadUtils.sleep(1000);         }     });     ThreadUtils.sleep(1000);     future.cancel(true);     try {          future.get();     } catch (InterruptedException | CancellationException | ExecutionException e) {          e.printStackTrace();     }     ThreadUtils.sleep(1000 * 60); } 

此案例创建了只有一个线程的线程池,提交了一个死循序任务,该任务只调用ThreadUtils.sleep方法进入休眠。平常我们调用Thread.sleep方法都要求是否捕获中断异常,很多时候我们都会嫌弃麻烦,就用一个工具类提供sleep方法,然后将中断异常捕获,如ThreadUtils:

public class ThreadUtils {      public static void sleep(long millis) {          try {              Thread.sleep(millis);         } catch (InterruptedException ignored) {          }     } } 

此案例中,由于我们捕获了中断异常,因此这会导致任务并不会被终止,只是当我们调用future的get方法时会抛出CancellationException异常,如下图所示。

任务依然在运行中......

因此,在实际开发中,如果我们开发的Job也是如此,将会导致Job无法被中断取消,直至Job执行完成或者重启。在开发Job时,应当合理考虑是亿华云计算否要捕获中断异常。

如果我们希望案例中的任务能够被终止,我们可以这样处理:

@Test public void test() {      ExecutorService executorService = Executors.newSingleThreadExecutor();     Future<?> future = executorService.submit(() -> {          while (true) {              System.out.println( "rung....." );             try {                  Thread.sleep(1000);             } catch (InterruptedException ex) {                  System.err.println( "interrupted" );                 return; // 退出死循环             }         }     });     ThreadUtils.sleep(1000);     future.cancel(true);     try {          future.get();     } catch (InterruptedException | CancellationException | ExecutionException e) {          e.printStackTrace();     }     ThreadUtils.sleep(1000 * 60); } 

关于Thread的interrupt方法,注释描述的大致意思如下:

如果被中断的线程,当前是调用Object#wait、Thread#join、Thread#sleep方法,将收到InterruptedException,并且会清除中断标志; 如果此线程在I/O操作中(指java nio)被阻塞,调用interrupt方法通道将被关闭,线程将收到一个ClosedByInterruptException,并且会设置中断标志; ....

怎么理解中断标志呢?

“如果被中断的线程,当前是调用Object#wait、Thread#join、Thread#sleep方法,将收到InterruptedException,并且会清除中断标志”,案例中的代码正好符合这点,如果我们将案例代码改为如下:

@Test public void test() {      ExecutorService executorService = Executors.newSingleThreadExecutor();     Future<?> future = executorService.submit(() -> {          while (!Thread.interrupted()) {              System.out.println( "rung....." );             try {                  Thread.sleep(1000);             } catch (InterruptedException ex) {                  System.err.println( "interrupted" );             }         }     });     ThreadUtils.sleep(1000);     future.cancel(true);     try {          future.get();     } catch (InterruptedException | CancellationException | ExecutionException e) {          e.printStackTrace();     }     ThreadUtils.sleep(1000 * 60); } 

执行这段代码你会发现,死循环根本没有退出,正是因为Thread#sleep方法被中断,JVM并不会设置中断标志,只是抛出InterruptedException异常。

其它情况下,JVM只会设置中断标志,并不会抛出InterruptedException。如果我们不处理中断信号,那么中断信号并不会影响程序的继续执行。

@Test public void test2() {      ExecutorService executorService = Executors.newSingleThreadExecutor();     Future<?> future = executorService.submit(() -> {          int number = 0;         while (!Thread.interrupted()) {              number++;         }         System.out.println(number);     });     ThreadUtils.sleep(1000);     future.cancel(true);     try {          future.get();     } catch (InterruptedException | CancellationException | ExecutionException e) {          e.printStackTrace();     }     ThreadUtils.sleep(1000 * 60); } 

此案例并没有I/O操作导致的阻塞,因为调用中断方法后,线程只是设置了中断标志,我们用中断标志作为循序的退出条件,运行此案例,我们将看到,线程中断后,任务终止。反之,如果我们不处理中断标志,那么就等着IDEA进程卡掉吧。

很赞哦!(29115)