
interrupt可以影响sleep、wait,不能影响synchronized和lock。
在lock想要使用interrupt可以使用lockInterruptibly
package com.mashibing.juc.c_000_threadbasic;
import com.mashibing.util.SleepHelper;
import java.util.concurrent.locks.ReentrantLock;
/**
* interrupt与lockInterruptibly()
*/
public class T11_Interrupt_and_lockInterruptibly {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
lock.lock();
try {
SleepHelper.sleepSeconds(10);
} finally {
lock.unlock();
}
System.out.println("t1 end!");
});
t1.start();
SleepHelper.sleepSeconds(1);
Thread t2 = new Thread(() -> {
System.out.println("t2 start!");
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println("t2 end!");
});
t2.start();
SleepHelper.sleepSeconds(1);
t2.interrupt();
}
}
本文通过实例代码展示了Java中interrupt如何影响sleep和wait,以及如何在lock中使用lockInterruptibly来响应中断。代码创建了两个线程,t1使用常规方式获取并释放锁,t2则使用lockInterruptibly方法,当t2被中断时能够捕获InterruptedException并释放锁。
983

被折叠的 条评论
为什么被折叠?



