【Java】AQS同步队列结构分析
同步队列结构
AQS实现一个线程安全的计数器
自定义互斥锁
package com.rumenz.task.aqs;import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class MyLock {
private static final Sync STATE_HOLDER = new Sync();
/**
* 通过Sync内部类来持有同步状态, 当状态为1表示锁被持有,0表示锁处于空闲状态
*/
private static class Sync extends AbstractQueuedSynchronizer {
/**
* 是否被独占, 有两种表示方式
* 1. 可以根据状态,state=1表示锁被占用,0表示空闲
* 2. 可以根据当前独占锁的线程来判断,即getExclusiveOwnerThread()!=null 表示被独占
*/
@Override
protected boolean isHeldExclusively() {
return getExclusiveOwnerThread() != null;
}
/**
* 尝试获取锁,将状态从0修改为1,操作成功则将当前线程设置为当前独占锁的线程
*/
@Override
protected boolean tryAcquire(int arg) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
/**
* 释放锁,将状态修改为0
*/
@Override
protected boolean tryRelease(int arg) {
if (getState() == 0) {
throw new UnsupportedOperationException();
}
setExclusiveOwnerThread(null);
setState(0);
return true;
}
}
/**
* 下面的实现Lock接口需要重写的方法,基本是就是调用内部内Sync的方法
*/
public void lock() {
STATE_HOLDER.acquire(1);
}
public void unlock() {
STATE_HOLDER.release(1);
}
}
测试案例
package com.rumenz.task.aqs;import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class LockTest {
private final static Integer clientTotal=100000;
private final static Integer threadTotal=200;
private static Count count=new Count();
private static Count unSafe=new Count();
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
final Semaphore semaphore=new Semaphore(threadTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(()->{
try{
semaphore.acquire();
count.getIncrement();
unSafe.getUnSafeIncrement();
semaphore.release();
}catch (Exception e){
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println("safe:"+count.getCount());
System.out.println("unSafe:"+unSafe.getCount());
executorService.shutdown();
}
}
class Count{
private MyLock myLock;
private volatile int count;
Count() {
this.myLock=new MyLock();
}
int getCount(){
return count;
}
int getIncrement(){
myLock.lock();
count++;
myLock.unlock();
return count;
}
int getUnSafeIncrement(){
count++;
return count;
}
}
输出结果
safe:100000unSafe:99995
关注微信公众号:【入门小站】,解锁更多知识点
以上是 【Java】AQS同步队列结构分析 的全部内容, 来源链接: utcz.com/a/98060.html