博客
关于我
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 | doit,一个非常实用的 Python 库!
查看>>
python | easyocr,一个超厉害的 关于OCR的 Python 库!
查看>>
python | fastFM,一个高级的 Python 库!
查看>>
python | feature_engine,一个实用的 Python 库!
查看>>
python | filelock,一个超酷的 Python 库!
查看>>
python | fire,一个强大的 Python 库!
查看>>
python | flanker,一个神奇的 Python 库!
查看>>
python | flower,一个强大的 Python 库!
查看>>
python | funcy,一个超强的 提供函数式编程工具 Python 库!
查看>>