思想思考
什么是seamphore, 即信号量, 意思就是说 同步代码块只能允许一定数量的线程进入。超过这个信号量的线程需要阻塞。ok, 那就说明得有一个变量来记录 信号量最大限制, 以及有一个可以计数当前同步代码块中线程的数量。
使用 Synchronized实现
/**
*
* @Author: puhaiguo
* @Date: 2022-07-22 01:41
* @Version 1.0
*/
public class SynchronizedSeamphore {
private int limit;
private int curCount;
private Object moniter = new Object();
public SynchronizedSeamphore(int limit) {
this.limit = limit;
}
public void entry(){
synchronized (moniter){
while (curCount == limit){
try {
moniter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
curCount++;
moniter.notifyAll();
}
}
public void exit(){
synchronized (moniter){
moniter.notify();
curCount--;
}
}
}
使用AQS实现
/**
* 信号量
* @Author: puhaiguo
* @Date: 2022-07-22 01:03
* @Version 1.0
*/
public class MySeamphore {
private int limit;
private MyLock myLock;
public MySeamphore(int count) {
limit = count;
myLock = new MyLock(count);
}
private class MyLock extends MyAbstractQueueSynchronizer{
public MyLock(int count) {
setState(count);
}
public void lock(){
acquire(1);
}
@Override
protected boolean tryAcquire(int arg) {
int state = getState();
if (state == 0){
return false;
}else{
while (true){
if (state == 0) return false;
if (compareAndSetState(state, state-1)){
return true;
}
state = getState();
}
}
}
@Override
protected boolean tryRelease(int i) {
int state = getState();
while (true){
if (state == limit) throw new IllegalMonitorStateException();
if (compareAndSetState(state, state+1)){
return true;
}
state = getState();
}
}
}
public void entry(){
myLock.lock();
}
public void exit(){
myLock.release(1);
}
}
总结
呃, 如果使用Synchronized实现是比较简单,因为Synchronized提供了简单易用的api,而AQS实现就需要注意:应为入队 出队,作为共享锁,是存在线程安全问题的,所以需要使用cas补偿机制。。。