当a方法执行时不能继续执行a方法,但可以执行b方法;当b方法执行时可以继续执行b方法,但不能执行a方法,必须等待b方法全部执行完毕,才能执行a方法

查了很多资料,没有找到什么好的处理方式,就想到通过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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值