本文共 1754 字,大约阅读时间需要 5 分钟。
线程中断方法主要是两种:
.isInterrupted()
是否为中断状态 interrupt()
设置为中断 线程中断,并非真正的线程中断,而只是将线程的中断状态标识设置为true,由线程自己根据状态标识进行相应的业务处理逻辑,而线程实际上还在进行。
要区别于InterruptedException异常
,一般的,线程会因为BlockingQueue#put、BlockingQueue#take、Object#wait、Thread#sleep
以上状态被打断而抛出异常,这个异常是真正的线程中断,而与线程的中断状态标识没有任何关系,标识状态依然为false。
所以,这就需要注意一个问题,千万不能捕获了InterruptedException而不做中断处理,否则业务逻辑依然以为你没有中断,依然走正常的异常逻辑
@Testpublic void testThread() throws InterruptedException { testThread1(); testThread2();}private void testThread1() throws InterruptedException { Thread thread1 = new Thread(() -> { //判断当前线程的中断状态,否则执行,是则中断 while (!Thread.currentThread().isInterrupted()) { System.out.println("正常业务"); } System.out.println("中断业务"); }, "thread1"); thread1.start(); Thread.sleep(3000L); //中断线程1,并非真正的停止线程,而是将中断状态标识为true,由线程自己处理 thread1.interrupt();}private void testThread2() throws InterruptedException { Thread thread2 = new Thread(() -> { for (int i = 0; i < 5; i++) { boolean interrupted = Thread.currentThread().isInterrupted(); System.out.println("中断状态:" + interrupted); if (!interrupted) { try { System.out.println("业务逻辑"); Thread.sleep(3000);//模拟实际逻辑 } catch (InterruptedException e) { /*不可以吞掉异常,因为中断状态不会因为抛出异常而将interrupted改为true 故,必须设置中断,从而可以走中断业务逻辑 */ Thread.currentThread().interrupt(); } } else { System.out.println("中断业务逻辑"); } } }, "thread2"); thread2.start(); Thread.sleep(1000); thread2.interrupt();//模拟执行的正常业务逻辑出现异常}
转载地址:http://jtgzi.baihongyu.com/