lockInterruptibly 优先考虑响应中断,而不是响应锁定的普通获取或重入获取
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockTest {
public static void main(String[] args) throws InterruptedException {
// 该线程先获取锁1,再获取锁2
Thread thread = new Thread(new ThreadDemo());
// 该线程先获取锁2,再获取锁1
Thread thread1 = new Thread(new ThreadDemo());
thread.start();
thread1.start();
// 是第2个线程中断
thread1.interrupt();
}
static class ThreadDemo implements Runnable {
private static Lock lock = new ReentrantLock();
@Override
public void run() {
try {
//
lock.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + " 开始");
System.out.println("休息5s----");
TimeUnit.SECONDS.sleep(5);
lock.unlock();
System.out.println(Thread.currentThread().getName() + "正常结束!");
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " 中断了");
}
}
}
}
结果是
如果改成lock.lock();
结果为