Semaphore类相关总结

Semaphore的使用大致是对Synchronize的增强,控制执行的线程数
public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        ExecutorService pool = Executors.newFixedThreadPool(10);
        int i = 10;
        do {
            pool.execute(() -> doSomething(semaphore));
            i--;
        } while (i != 0);
        Thread.sleep(50000);
    }

    private static void doSomething(Semaphore semaphore)  {
        try {
            semaphore.acquire();
            System.out.println("开始执行");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println("结束执行");
            semaphore.release();
        }
    }
}

实现Synchronize的功能,并且在初始化Semaphore的时候可以设置并发量。

内部实现:Sync类继承的AQS

发布了85 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/New_CJ/article/details/93876344
今日推荐