1,ReentrantLock的lock()不会再获锁过程中去响应中断标志。而是再获取锁之后才响应中断。
2,ReentrantLock.lockInterruptibly允许在等待时由其它线程调用等待线程的Thread.interrupt方法来中断等待线程的等待而直接返回,这时不用获取锁,而会抛出一个InterruptedException。
代码示例:
1.使用lockInterruptibly()的情况:
public class ReentrantLockInterruptibly {
private Lock lock = new ReentrantLock();
public void doBussiness() {
String name = Thread.currentThread().getName();
try {
System.out.println(name + " 开始获取锁");
lock.lockInterruptibly();
System.out.println(name + " 得到锁");
System.out.println(name + " 开工干活");
for (int i=0; i<5; i++) {
Thread.sleep(1000);
System.out.println(name + " : " + i);
}
} catch (InterruptedException e) {
System.out.println(name + " 被中断");
System.out.println(name + " 做些别的事情");
} finally {
try {
lock.unlock();
System.out.println(name + " 释放锁");
} catch (Exception e) {
System.out.println(name + " : 没有得到锁的线程运行结束");
}
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockInterruptibly lockTest = new ReentrantLockInterruptibly();
Thread t0 = new Thread(lockTest::doBussiness);
Thread t1 = new Thread(lockTest::doBussiness);
// 启动线程t1
t0.start();
Thread.sleep(10);
// 启动线程t2
t1.start();
t1.interrupt();
}
}
返回结果:
Thread-0 开始获取锁
Thread-0 得到锁
Thread-0 开工干活
Thread-1 开始获取锁
Thread-1 被中断
Thread-1 做些别的事情
Thread-1 : 没有得到锁的线程运行结束
Thread-0 : 0
Thread-0 : 1
Thread-0 : 2
Thread-0 : 3
Thread-0 : 4
Thread-0 释放锁
即当thread-0持有了锁在进行任务执行的过程中,主线程使用t1.interrupt();中断了t1线程,使用lock.lockInterruptibly();会立马抛出一个InterruptedException 并进行之后的操作
2.使用lock.lock()情况
public class ReentrantLockInterruptibly {
private Lock lock = new ReentrantLock();
public void doBussiness() {
String name = Thread.currentThread().getName();
try {
System.out.println(name + " 开始获取锁");
lock.lock();
System.out.println(name + " 得到锁");
System.out.println(name + " 开工干活");
for (int i=0; i<5; i++) {
Thread.sleep(1000);
System.out.println(name + " : " + i);
}
} catch (InterruptedException e) {
System.out.println(name + " 被中断");
System.out.println(name + " 做些别的事情");
} finally {
try {
lock.unlock();
System.out.println(name + " 释放锁");
} catch (Exception e) {
System.out.println(name + " : 没有得到锁的线程运行结束");
}
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockInterruptibly lockTest = new ReentrantLockInterruptibly();
Thread t0 = new Thread(lockTest::doBussiness);
Thread t1 = new Thread(lockTest::doBussiness);
// 启动线程t1
t0.start();
Thread.sleep(10);
// 启动线程t2
t1.start();
t1.interrupt();
}
}
返回结果:
Thread-0 开始获取锁
Thread-0 得到锁
Thread-0 开工干活
Thread-1 开始获取锁
Thread-0 : 0
Thread-0 : 1
Thread-0 : 2
Thread-0 : 3
Thread-0 : 4
Thread-0 释放锁
Thread-1 得到锁
Thread-1 开工干活
Thread-1 被中断
Thread-1 做些别的事情
即:在t0线程持有锁并任务执行的过程中,主线程中断了t1线程,但是我们发现,此时t1线程不会立即响应中断标志,而是在t0释放锁之后,去拿到锁了之后,才去响应这个中断标志。