博客
关于我
ReentranLock源码分析
阅读量:265 次
发布时间:2019-03-01

本文共 2070 字,大约阅读时间需要 6 分钟。

ReentrantLock ?????????

ReentrantLock ? Java ?????????????????????????????????????????????????????????? AbstractQueuedSynchronizer (AQS) ?????CAS??????????????????

1. ??

ReentrantLock ??? Lock ?????? lock() ? unlock() ?????? newCondition() ????????????????????????????????????????????

2. ????

ReentrantLock ????????Sync?NonfairSync ? FairSync????NonfairSync ? FairSync ??? Sync?Sync ???? AbstractQueuedSynchronizer?

2.1 Sync ?

Sync ?? ReentrantLock ???????????????????????? nonfairTryAcquire()?tryRelease() ??

nonfairTryAcquire()

  • ????????????????
  • ????????state == 0????? CAS ??????
  • ????????????????????
  • ????????? false?

tryRelease()

  • ????????????????
  • ????????????? IllegalMonitorStateException?
  • ???????????????????
  • ???????????????

2.2 NonfairSync ?

NonfairSync ????????????????????? lock() ???? CAS ???????????????????????

acquire()

  • ??? nonfairTryAcquire() ????
  • ???????????????

addWaiter()

  • ???????????????
  • ?? CAS ???????????

acquireQueued()

  • ??????????????
  • ?????????? SIGNAL???????
  • ??????????????????

2.3 FairSync ?

FairSync ?????????? lock() ???? acquire(1) ????????????????????????????????????????????????

3. ????

3.1 ?????

public class TestReentrantLock {    private static Lock lock = new ReentrantLock();    public static void main(String[] args) {        MyThread t1 = new MyThread("t1", lock);        MyThread t2 = new MyThread("t2", lock);        MyThread t3 = new MyThread("t3", lock);        t1.start();        t2.start();        t3.start();    }    static class MyThread extends Thread {        private Lock lock;        MyThread(String name, Lock lock) {            super(name);            this.lock = lock;        }        public void run() {            lock.lock();            try {                System.out.println(Thread.currentThread().getName() + " running");                Thread.sleep(500);            } catch (InterruptedException e) {                e.printStackTrace();            } finally {                lock.unlock();            }        }    }}

3.2 ????

????????????????????????????????????

?????????????? ReentrantLock ?????????????????????

转载地址:http://qbtx.baihongyu.com/

你可能感兴趣的文章
python读取json数据的id_python处理JSON数据
查看>>
Python 中的Duck Typing
查看>>
Python 中的for in 遍历生成字典、添加判断条件if
查看>>
Python 中的Lock与RLock
查看>>
Python 中的range(),arange()函数
查看>>
Python 中的内存管理机制
查看>>
Python 中的函数包装器:模型运行时和调试
查看>>
Python 中的列表理解和 lambda
查看>>
Python 中的多层for in嵌套循环使用
查看>>
Python 中的多线程(01/4)
查看>>
Python 中的多进程(01/2):简介
查看>>
Python 中的多进程(02/2):进程之间的通信)
查看>>
Python 中的字符串、列表、元组和字典数据类型的特点和使用场景
查看>>
Python 中的属性访问器是什么?如何使用 @property 装饰器?
查看>>
Python 中的带宽限制
查看>>
Python 中的机器学习简介:多项式回归
查看>>
python读取grib2数据_用Python加载grib2文件
查看>>
Python 中的注意点_s2
查看>>
Python读取Excel的几种工具包(附Demo)
查看>>
Python 中的生成器是什么?
查看>>