标签:有一个 异常 blog none max flow comment release ace
public void unlock() {
sync.release();
}
public final boolean tryRelease( int releases) {
// 如果不是锁持有者,则调用 unlock则抛出异常
int c = getState() - releases;
if(Thread.currentThread() != getExclusiveOwnerThread()) {
throw new IllegalMonitorStateException();
}
boolean free = false;
// 如果当前可重入的次数为0,则清空锁持有线程
if(c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
// 设置可重入次数为原始值-1
setState(c);
return free;
}
package com.ruigege.LockSourceAnalysis6;
import java.util.ArrayList;
public static class ReentrantLockList {
//线程不安全的List
private ArrayList<String> array = new ArrayList<String>();
//独占锁
private volatile ReentrantLock lock = new ReentrantLock();
//添加元素
public void add(String e) {
lock.lock();
try {
array.add(e);
}finally {
lcok.unlock();
}
}
//删除元素
public void remove(String e) {
lock.lock();
try {
array.remove(e);
}finally {
lock.unlock();
}
}
//获取数据
public String get(int index) {
lock.lock();
try {
return array.get(index);
}finally {
lock.unlock();
}
}
}
https://github.com/ruigege66/ConcurrentJava
Java高并发26-释放锁以及ReentrantLock实例演示
标签:有一个 异常 blog none max flow comment release ace
原文地址:https://www.cnblogs.com/ruigege0000/p/14665173.html