1、semaphore(信号量)
1.1、概念
1.2、示例代码
AQSDemo是对AQS的简写
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
/** 此类是一个简单版的AQS,AQS的大致结构就是如此,其中以try开头的方法需要子类具体实现,用到了模板方法设计模式,这些方法又称为钩子方法 */
public class AQSdemo {
// 同步资源状态
volatile AtomicInteger state = new AtomicInteger(0);
// 当前锁的拥有者
protected volatile AtomicReference<Thread> owner = new AtomicReference<>();
// java q 线程安全
public volatile LinkedBlockingQueue<Thread> waiters = new LinkedBlockingQueue<>();
// 独占
public void acquire() {
// 塞到等待锁的集合中
waiters.offer(Thread.currentThread());
while (!tryAcquire()) {
// 挂起这个线程
LockSupport.park();
}
// 后续,等待其他线程释放锁,收到通知之后继续循环
waiters.remove(Thread.currentThread());
}
public void release() {
// cas 修改 owner 拥有者
if (tryRelease()) {
Thread waiter = waiters.peek();
LockSupport.unpark(waiter); // 唤醒线程继续 抢锁
}
}
public boolean tryAcquire() {
throw new UnsupportedOperationException();
}
public boolean tryRelease() {
throw new UnsupportedOperationException();
}
// 共享资源获取
public void acquireShared() {
// 塞到等待锁的集合中
waiters.offer(Thread.currentThread());
while (tryAcquireShared() < 0) {
// 挂起这个线程
LockSupport.park();
}
// 后续,等待其他线程释放锁,收到通知之后继续循环
waiters.remove(Thread.currentThread());
}
// 共享资源的释放
public void releaseShared() {
// cas 修改 owner 拥有者
if (tryReleaseShared()) {
Thread waiter = waiters.peek();
LockSupport.unpark(waiter); // 唤醒线程继续 抢锁
}
}
public int tryAcquireShared() {
throw new UnsupportedOperationException();
}
public boolean tryReleaseShared() {
throw new UnsupportedOperationException();
}
public AtomicInteger getState() {
return state;
}
public void setState(AtomicInteger state) {
this.state = state;
}
}
信号量的应用
import com.study.lock.aqs.AQSdemo;
// 自定义的信号量实现
public class NeteaseSemaphore {
AQSdemo aqs = new AQSdemo() {
@Override
public int tryAcquireShared() { // 信号量获取, 数量 - 1
for(;;) {
int count = getState().get();
int n = count - 1;
if(count <= 0 || n < 0) {
return -1;
}
if(getState().compareAndSet(count, n)) {
return 1;
}
}
}
@Override
public boolean tryReleaseShared() { // state + 1
return getState().incrementAndGet() >= 0;
}
};
/** 许可数量 */
public NeteaseSemaphore(int count) {
aqs.getState().set(count); // 设置资源的状态
}
public void acquire() {
aqs.acquireShared();
} // 获取令牌
public void release() {
aqs.releaseShared();
} // 释放令牌
}
import com.study.lock.aqs.AQSdemo;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
// 信号量机制
public class SemaphoreDemo {
public static void main(String[] args) {
SemaphoreDemo semaphoreTest = new SemaphoreDemo();
int N = 9; // 客人数量
MySemaphore semaphore = new MySemaphore(5); // 手牌数量,限制请求数量
for (int i = 0; i < N; i++) {
String vipNo = "vip-00" + i;
new Thread(() -> {
try {
semaphore.acquire(); // 获取令牌,没拿到的就等
System.out.println(semaphore.count);
semaphoreTest.service(vipNo); // 实现了怼service方法的限流
semaphore.release(); // 释放令牌,令牌数+1
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
// 限流 控制5个线程 同时访问
public void service(String vipNo) throws InterruptedException {
System.out.println("楼上出来迎接贵宾一位,贵宾编号" + vipNo + ",...");
Thread.sleep(new Random().nextInt(3000));
System.out.println("欢送贵宾出门,贵宾编号" + vipNo);
}
}
2、CountdownLatch
2.1、概念
2.2、示例代码
import com.study.lock.aqs.AQSdemo;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
// CountDownLatch 自己实现
public class CDLdemo {
// Object AQS = new Oject(state, queue);
// AQS 具体实现对象(state、queue、owner)
AQSdemo aqSdemo = new AQSdemo() {
@Override
public int tryAcquireShared() { // 如果非等于0,代表当前还有线程没准备就绪,则认为需要等待
return this.getState().get() == 0 ? 1 : -1;
}
@Override
public boolean tryReleaseShared() { // 如果非等于0,代表当前还有线程没准备就绪,则不会通知继续执行
return this.getState().decrementAndGet() == 0;
}
};
public CDLdemo(int count) {
aqSdemo.setState(new AtomicInteger(count));
}
public void await() {
aqSdemo.acquireShared();
}
public void countDown() {
aqSdemo.releaseShared();
}
public static void main(String[] args) throws InterruptedException {
// 一个请求,后台需要调用多个接口 查询数据
CDLdemo cdLdemo = new CDLdemo(10); // 创建,计数数值
for (int i = 0; i < 10; i++) { // 启动九个线程,最后一个两秒后启动
int finalI = i;
new Thread(() -> {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我是" + Thread.currentThread() + ".我执行接口-" + finalI +"调用了");
cdLdemo.countDown(); // 参与计数
// 不影响后续操作
}).start();
}
cdLdemo.await(); // 等待计数器为0
System.out.println("全部执行完毕.我来召唤神龙");
}
}
3、CyclicBarrier
3.1、概念
3.2、示例代码
import java.util.ArrayList;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
// 循环屏障(栅栏),示例:数据库批量插入
// 游戏大厅... 5人组队打副本
public class CyclicBarrierTest {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<String> sqls = new LinkedBlockingQueue<>();
// 任务1+2+3...1000 拆分为100个任务(1+..10, 11+20) -> 100线程去处理。
// 每当有4个线程处于await状态的时候,则会触发barrierAction执行
CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
@Override
public void run() {
// 这是每满足4次数据库操作,就触发一次批量执行
System.out.println("有4个线程执行了,开始批量插入: " + Thread.currentThread());
for (int i = 0; i < 4; i++) {
System.out.println(sqls.poll());
}
}
});
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
sqls.add("data - " + Thread.currentThread()); // 缓存起来
Thread.sleep(1000L); // 模拟数据库操作耗时
barrier.await(); // 等待栅栏打开,有4个线程都执行到这段代码的时候,才会继续往下执行
System.out.println(Thread.currentThread() + "插入完毕");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
Thread.sleep(2000);
}
}