获取线程是否被打断
打断线程
获取线程是否被打断,如果被打断,复位。
1.3个方法使用示例:
public static void main(String[] args) {Thread t1 = new Thread(() -> {System.out.println("初始状态:"+Thread.currentThread().isInterrupted());while(true) {if(Thread.currentThread().isInterrupted()) {System.out.println("被打断状态:"+Thread.currentThread().isInterrupted());// 复位boolean interrupted = Thread.interrupted();System.out.println("复位返回值:"+interrupted);System.out.println("复位后状态:"+Thread.currentThread().isInterrupted());}}});t1.start();try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}t1.interrupt();}
控制台输出:
初始状态:false
被打断状态:true
复位返回值:true
复位后状态:false
2.由实验得出的结论:当catch注InterruptedException,JVM会认为程序已经处理了打断,会自动复位打断状态。代码:
public static void main(String[] args) {Thread t1 = new Thread(() -> {System.out.println("初始状态:"+Thread.currentThread().isInterrupted());synchronized (WaitDemo.class) {try {WaitDemo.class.wait();} catch (InterruptedException e) {System.out.println("被打断状态:"+Thread.currentThread().isInterrupted());// 复位boolean interrupted = Thread.interrupted();System.out.println("复位返回值:"+interrupted);}System.out.println("复位后状态:"+Thread.currentThread().isInterrupted());}});t1.start();try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}t1.interrupt();}
控制台输出:
初始状态:false
被打断状态:false
复位返回值:false
复位后状态:false
不可以,代码:
public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(() -> {synchronized (args) {try {Thread.sleep(5000);} catch (InterruptedException e) {System.out.println("被打断了");}}});t1.start();Thread t2 = new Thread(() -> {synchronized (args) {}System.out.println("输出t2");});t2.start();Thread.sleep(1000);t2.interrupt();}
程序执行结果:5秒后才输出t2,证明t2没有被打断
lock()方法并不能被打断。与synchronized同理
但lockInterruptibly()方法可以被打断。
代码:
public static void main(String[] args) throws InterruptedException {Lock lock = new ReentrantLock();Thread t1 = new Thread(() -> {lock.lock();System.out.println("输出t1");try {Thread.sleep(10000);} catch (InterruptedException e) {System.out.println("t1被打断了");}lock.unlock();});t1.start();Thread t2 = new Thread(() -> {try {lock.lockInterruptibly();} catch (InterruptedException e) {System.out.println("t2被打断了");}System.out.println("输出t2");});t2.start();Thread.sleep(2000);t2.interrupt();}
本文发布于:2024-01-27 21:16:59,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063614172690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |