下面是使用信号量限制并发访问的一个简单例子
package com.example.demo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author xiaochi
* @date 2022/6/23 10:30
* @desc SemaphoreTest
*/
public class SemaphoreTest {
private static final ExecutorService executorService = Executors.newFixedThreadPool(100);
private static final Semaphore semaphore = new Semaphore(10);
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
System.out.println("Request processing ...");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
}
}
这里我们创建了 100 个线程同时执行,但是由于信号量计数为 10,所以同时只能有 10 个线程在处理请求。说到计数,实际上,在 Java 里除了 Semaphore 还有很多类也可以用作计数,比如 AtomicLong 或 LongAdder,这在并发量限流中非常常见,只是无法提供像信号量那样的阻塞能力
package com.example.demo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author xiaochi
* @date 2022/6/23 10:56
* @desc AtomicLongTest
*/
public class AtomicLongTest {
private static final ExecutorService executorService = Executors.newFixedThreadPool(100);
private static final AtomicLong atomic = new AtomicLong();
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
executorService.execute(() -> {
long val = atomic.incrementAndGet();
System.out.println("值:"+val);
if (val > 10){
System.out.println("Request rejected ...");
return;
}
System.out.println("Request processing ...");
atomic.decrementAndGet();
});
}
executorService.shutdown();
}
}
这里只是单机限流,如果使用分布式可以使用 redission,提供分布式的信号量与分布式锁等等这些
网友评论