lockInterruptibly 与 lock比较区别
- lock 优先考虑获取锁,待获取锁成功后,才响应中断。
- lockInterruptibly 优先考虑响应中断,而不是响应锁的普通获取或重入获取。
- ReentrantLock.lockInterruptibly允许在等待时由其它线程调用等待线程的Thread.interrupt方法来中断等待线程的等待而直接返回,这时不用获取锁,而会抛出一个InterruptedException。 ReentrantLock.lock方法不允许Thread.interrupt中断,即使检测到Thread.isInterrupted,一样会继续尝试获取锁,失败则继续休眠。只是在最后获取锁成功后再把当前线程置为interrupted状态,然后再中断线程。
代码示例:
package test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TTTT {
public static void main(String[] args){
Thread i1 = new Thread(new RunIt3());
Thread i2 = new Thread(new RunIt3());
i1.start();
i2.start();
i2.interrupt();
}
}
class RunIt3 implements Runnable{
private static Lock lock = new ReentrantLock();
public void run(){
try{
lock.lock();
System.out.println(Thread.currentThread().getName() + " running");
TimeUnit.SECONDS.sleep(20);
lock.unlock();
System.out.println(Thread.currentThread().getName() + " finished");
}
catch (InterruptedException e){
System.out.println(Thread.currentThread().getName() + " interrupted");
}
}
}
lock.lock()结果说明:
如果a处 是lock.lock();
输出
Thread-0 running
(这里休眠了20s)
Thread-0 finished
Thread-1 running
Thread-1 interrupted
lock.lockInterruptibly() 结果说明:
如果a处是lock.lockInterruptibly()
Thread-0 running
Thread-1 interrupted
(这里休眠了20s)
Thread-0 finished