Java并发25:Semaphore与Exchanger - 控制并发与数据交换

Semaphore:信号量 核心概念:控制同时访问资源的线程数 Semaphore semaphore = new Semaphore(3); // 3个许可证 semaphore.acquire(); // 获取许可证(阻塞) try { // 访问资源 } finally { semaphore.release(); // 释放许可证 } 应用场景 场景1:限流(数据库连接池) public class ConnectionPool { private final Semaphore semaphore; private final List<Connection> connections; public ConnectionPool(int size) { this.semaphore = new Semaphore(size); this.connections = new ArrayList<>(size); for (int i = 0; i < size; i++) { connections.add(createConnection()); } } public Connection getConnection() throws InterruptedException { semaphore.acquire(); // 获取许可证 return connections.remove(0); } public void releaseConnection(Connection conn) { connections.add(conn); semaphore.release(); // 释放许可证 } } 场景2:限制并发访问 ...

2025-11-20 · maneng

如约数科科技工作室

浙ICP备2025203501号

👀 本站总访问量 ...| 👤 访客数 ...| 📅 今日访问 ...