例子
lock()
public class LockTest1 {
void testLock() throws InterruptedException {
final Lock lock = new ReentrantLock();
lock.lock();
Thread t1 = new Thread(() -> {
lock.lock();
System.out.println(Thread.currentThread().getName());
}, "t1-thread");
t1.start();
Thread.sleep(1000);
t1.interrupt();
Thread.sleep(10000);
}
public static void main(String[] args) throws InterruptedException {
new LockTest1().testLock();
}
}
以上这段程序,会一直阻塞,没有结果输出。
lockInterruptibly()
void testLock() throws InterruptedException {
final Lock lock = new ReentrantLock();
lock.lock();
Thread t1 = new Thread(() -> {
// lock.lock();
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}, "t1-thread");
t1.start();
Thread.sleep(1000);
t1.interrupt();
Thread.sleep(10000);
}
但如果把t1线程中的lock()方法改掉,改成如上,则会输出 以下结果