介绍
基于Semaphore的功能,主要用来实现并发和限流,本文采用synchronized来实现Semaphore基础功能。关于Semaphore的说明,请参考JDK1.8 信号量(Semaphore)的基本使用
代码实现
public class MySemaphore {
private volatile int count;
private volatile int waitCount = 0;
/**
* 初始化信号量
* @param count
*/
public MySemaphore(int count) {
this.count = count;
}
/**
* 获取信号量
* @throws InterruptedException
*/
public void acquire() throws InterruptedException {
while (true) {
//大量线程在此处等锁
//执行wait的线程被唤醒后, 重新加入抢锁操作
waitCount++;
synchronized (this) {
if (this.count > 0) {
this.count--;
waitCount--;
break;
}
this.wait();
}
waitCount--;
//退出synchronized代码块,释放锁
}
}
/**
* 释放锁,通知所有等待线程进行抢锁
*/
public void release() {
synchronized (this) {
this.count++;
this.notifyAll();
}
}
/**
* 可用的信号量
* @return
*/
public int availablePermits(){
return this.count;
}
/**
* 阻塞线程的个数
* @return
*/
public int getQueueLength(){
return waitCount;
}
}
上述代码主要实现了acquire(),release(),availablePermits()和getQueueLength()最基础的功能。
测试代码
package sample;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
// Semaphore semaphore=new Semaphore(24);
MySemaphore semaphore = new MySemaphore(24);
// int count = semaphore.availablePermits();
// System.out.println("可用信号量 count1: " + count);
// //增加20个信号量
// semaphore.release(20);
int count = semaphore.availablePermits();
//此时信号量个数为24个, 可以支持同时跑24个线程
System.out.println("可用信号量 count2: " + count);
for (int i = 0; i < 200; i ++){
new Thread(()->{
try {
semaphore.acquire();
System.out.println("" + Thread.currentThread().getName() + " 进入" + " 时间: " + System.currentTimeMillis());
Thread.sleep(200);
System.out.println("" + Thread.currentThread().getName() + " 退出" + " 时间: " + System.currentTimeMillis());
semap