允许在等待时由其他线程的Thread.interrupt()方法来中断等待线程
lockInterruptibly 与 lock比较区别在于
lockInterruptibly 优先考虑响应中断,也就是说在lock.lockInterruptibly();之后的代码不会执行,直接就被异常捕获了。
而lock.lock();则是会一直到调用sleep函数后才响应,sleep函数之前的代码会照常执行,之后还会继续尝试获取锁
像下面的代码
public class test{
private Lock lock = new ReentrantLock();//重入锁
private int tickets = 20;
public static void main(String[] args) {
ReentrantLockDemo reentrantLockDemo = new test().new ReentrantLockDemo();
Thread thread = new Thread(reentrantLockDemo);
thread.start();
thread.interrupt();
}
class ReentrantLockDemo implements Runnable{
@Override
public void run() {
while(true) {
try {
lock.lock();
// lock.lockInterruptibly();
if(tickets > 0) {
System.out.println("thread start tickets="+tickets);
TimeUnit.MICROSECONDS.sleep(100);
System.out.println(Thread.currentThread().getName() + "--" + tickets--);
}else {
break;
}
} catch (Exception e) {
System.out.println("stop--" + Thread.currentThread().getName());
e.printStackTrace();
}finally {
lock.unlock();
}
System.out.println("while end");
}
}
}
}
lock.lock的运行结果如下,
lock.lockInterruptibly的结果如下