今天在看Lock,都知道相比于synchronized,多了公平锁,可中断等优秀性能。

但是说到可中断这个特点,看到很多博客是这么描述的:

“与synchronized关键字不同,获取到锁的线程能够响应中断,当获取到锁的线程被中断时,中断异常将会被抛出,同时锁会被释放”

我的理解是,应该是未获得到锁的线程被中断时,中断异常将会被抛出。

看了下lockInterruptibly()的源码

第一层

public void lockInterruptibly() throws InterruptedException {

    sync.acquireInterruptibly(1);
}
第二层
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
第3层
private void doAcquireInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}

其实就是调用lockInterruptibly()时,第二层中判断当前线程是否中断Thread.interrupted() 如果是,抛异常
以及第三层中 一个for(;;)循环一直判断当前线程是否有中断标志。(代码中大字标识部分)

所以不是很理解很多博客中说的这种情况。

总结:lock中的可中断特性是基于lockInterruptibly()方法的,它是对于那些未竞争的到锁,而 可以被外部调用interrupt()来中断,从而达到不在等候锁资源,不再去竞争锁

最新文章

  1. 使用mapreduce计算环比的实例
  2. 《Note --- Unreal 4 --- B project --- Second UV issue》
  3. 如何关闭eslint
  4. Nudnik Photographer -Ural1260动态规划
  5. JNDI 是什么
  6. EntityFramework Code First 优化-IIS 8的第一次优化请求配置
  7. IsPostBack
  8. Android开发文摘集合1
  9. dedecms由子目录访问修改为根目录访问
  10. css部分总结
  11. 制作简易计算器处理过程Servlet
  12. html readonly和disabled的区别
  13. OpenvSwitch Port Mirror in OpenStack Neutron
  14. yii2 httpClient的用法
  15. PHP Xdebug + PhpStorm调试远程服务器代码
  16. Angularjs实现select的下拉列表
  17. django实现分页
  18. [MySQL]在安装windows版MySQL时遇到过如下问题Error Nr.1045和Error.Nr.2003,相应解决办法如下
  19. [Angular-Scaled web] 1. Architecture and file structure
  20. Bootstrap-Other:可视化布局

热门文章

  1. IDEA 导入 Maven 项目后报错 cannot resolve symbol 解决办法
  2. 人人都是 API 设计师:我对 RESTful API、GraphQL、RPC API 的思考
  3. ELK 学习笔记之 Logstash之inputs配置
  4. MongoDB 学习笔记之 索引
  5. python的闭包操作
  6. SLAM中的卡方分布
  7. 调用对象 “ha-datastoresystem”的“HostDatastoreSystem.QueryVmfsDatastoreCreateOptions” 失败。
  8. 最简单的ArcGIS Engine应用程序(中)
  9. vue中methods,computed,filters,watch的总结
  10. Python开发【第五篇】字符串