Java并发编程 - AQS 之 Semaphore(三)

tryAcquire 用法

  • 尝试获取一个许可,参数有:许可数,等待时间,时间单位。
  • 表示:在规定时间内等待,超过时间则抛弃。
package com.mmall.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SemaphoreExample3 {

    private final static int threadCount = 20;

    public static void main(String[] args) throws Exception {

        ExecutorService exec = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    if (semaphore.tryAcquire()) { // 尝试获取一个许可
                        test(threadNum);
                        semaphore.release(); // 释放一个许可
                    }
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        log.info("{}", threadNum);
        Thread.sleep(1000);
    }
}

// 输出
0
2
1

分析

  • 之前一直以为 acquire 是规定时间内,如果没获取到的就丢弃了,其实还是太年轻了,并不是这样的。
  • acquire 在上一篇讲解到,如果阻塞住,就一直程序还是在跑的,而这个 tryAcquire 是真的规定时间内,没获取到的就丢弃了。
  • 所以你会发现上面才输出 3 条。
发布了1005 篇原创文章 · 获赞 1889 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/105517959