温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解java中的中断机制

发布时间:2021-01-05 14:56:45 来源:亿速云 阅读:124 作者:Leah 栏目:开发技术

详解java中的中断机制?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

java 中断api

interrupt()

interrupt()方法本质上就是通过调用java.lang.Thread#interrupt0设置中断flag为true,如下代码演示了该方法的使用: 另启一个线程中断了当前线程。

@Test
public void interruptSt() {
 Thread mainThread = Thread.currentThread();
 new Thread(/*将当前线程中断*/mainThread::interrupt).start();
 try {
 //public static native void sleep(long millis) throws InterruptedException;
 Thread.sleep(1_000);
 } catch (InterruptedException e) {
 System.out.println("main 线程被中断了");
 }
 /*
 * 输出: main 线程被中断了
 */
}

interrupted()和isInterrupted()

public boolean isInterrupted() {
 // 设置this线程的中断flag,不会重置中断flag为true
 return isInterrupted(false);
}
public /*静态方法*/static boolean interrupted() {
 // 设置当前线程的中断flag,重置中断flag为true
 return currentThread().isInterrupted(true);
}

使用示例

@Test
public void test_Flag() {
 Thread currentThread = Thread.currentThread();
 currentThread.interrupt();
 System.out.println("当前线程状态 =" + currentThread.isInterrupted());
 System.out.println("当前线程状态 =" + Thread.interrupted());
 System.out.println("当前线程状态 =" + Thread.interrupted());
 /* 输出
 当前线程状态 =true
 当前线程状态 =true
 当前线程状态 =false*/
}

三、如何响应中断?

调用一个可中断的阻塞方法时需要处理受检异常InterruptException,一般来说最容易的方式就是继续抛出InterruptException ,让调用方决定对中断事件作出什么应对。但是对于一些不能在方法头直接添加异常声明的,可以catch出后再进行一些操作,例如使用Runnable时:

详解java中的中断机制

一般来说当catch到中断时,应该对中断状态进行还原: 调用Thread.currentThread().interrupt();,除非明确自己的操作不会丢失线程中断的证据,从而剥夺了上层栈的代码处理中断的机会。

总结

对目标线程调用interrupt()方法可以请求中断一个线程,目标线程通过检测isInterrupted()标志获取自身是否已中断。如果目标线程处于阻塞状态,该线程会捕获到InterruptedException。一般来说不要catchInterruptException后不做处理(“生吞中断”)。

看完上述内容,你们掌握详解java中的中断机制的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI