查了很多资料,没有找到什么好的处理方式,就想到通过while和Semaphore进行控制。
如果有更好的方式,或者有相关的锁可以进行控制处理,有劳大佬告诉我一下
分布式服务中,使用redisson。
RSemaphore semaphore = redissonClient.getSemaphore("RSemaphore");
String lockKey = "redis.lock:" + "RLock";
RLock lock = redissonClient.getLock(lockKey);
主要通过许可数的数量进行控制,执行b方法许可数+1,b方法执行完毕许可数-1;如果许可数=0则跳出while循环。具体代码如下
private static int x = 0;
private static void executorServiceRealization(int type, Semaphore semaphore) {
int totalCount = 30;
ExecutorService executorService = new ThreadPoolExecutor(5,
20,
0L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(30),
new ThreadPoolExecutor.AbortPolicy());
try {
for (int i = 0; i < totalCount; i++) {
executorService.execute(() -> {
if (type == 1) {
a(semaphore);
}
if (type == 2) {
b(semaphore);
}
});
}
} finally {
executorService.shutdown();
}
}
private static synchronized void a(Semaphore semaphore) {
while (semaphore.availablePermits() > 0) {
log.info("b方法正在使用{}", semaphore.availablePermits());
}
x++;
log.info("a方法执行{}", x);
}
private static void b(Semaphore semaphore) {
try {
semaphore.release();
Thread.sleep(1000L);
} catch (InterruptedException e) {
log.info("异常:{}", CommonUtils.getStackTraceString(e));
} finally {
try {
semaphore.acquire();
} catch (InterruptedException e) {
log.info("休眠:{}", CommonUtils.getStackTraceString(e));
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(0);
executorServiceRealization(1, semaphore);
executorServiceRealization(2, semaphore);
}