标签:next max row except lock space overflow nfa vat
private Lock lock = new ReentrantLock(); public void test(){ lock.lock(); try{ do(); }catch (Exception e){ throw e; }finally { lock.unlock(); } }
reentrantlock和synchronized很像 都是重入锁
但是感觉reentrantlock更加强大
final void lock() { //cas方法比较状态是否为1,如果为0,就把状态改为1,并获得锁 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); //否则就再次请求一次。 else acquire(1); }
acquire源码
/**抢占模式或者非公平锁*/ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //会在去比较一次 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } //是自己占有了锁,重入锁,那就可以再次获得锁,然后修改state } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; }
从上面可以看出重入锁只是指的是 如果当前线程拥有资源的锁时候,就可以再次获得锁资源
标签:next max row except lock space overflow nfa vat
原文地址:https://www.cnblogs.com/tecnologycc/p/9870685.html