public class Counter { private static final Semaphore SEMAPHORE = new Semaphore(1); private static int count; // 用信号量保证互斥 public static void addOne() throws InterruptedException { // 原子操作 SEMAPHORE.acquire(); try { count += 1; } finally { // 原子操作 SEMAPHORE.release(); } } }
public class ObjPool<T, R> { private final List<T> pool; // 用信号量实现限流器 private final Semaphore semaphore; public ObjPool(int size, T t) { // 信号量允许多个线程进入临界区,因此采用并发安全的Vector pool = new Vector<T>(); for (int i = 0; i < size; i++) { pool.add(t); } semaphore = new Semaphore(size); } // 利用对象池中的对象,调用func public R exec(Function<T, R> func) throws InterruptedException { T t = null; semaphore.acquire(); try { // 分配对象 t = pool.remove(0); return func.apply(t); } finally { // 释放对象 pool.add(t); semaphore.release(); } } public static void main(String[] args) throws InterruptedException { // 创建对象池 ObjPool<Long, String> objPool = new ObjPool<>(10, 2L); // 通过对象池获取t后执行 objPool.exec(t -> { System.out.println(t); return t.toString(); }); } }
转载请注明出处:http://zhongmingmao.me/2019/05/08/java-concurrent-semaphore/
访问原文「 Java并发 -- Semaphore 」获取最佳阅读体验并参与讨论