2025-09-29 250929-Java-Semaphore信号量多线程并发控制 多线程并发信号量控制逻辑123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/**/private static final ConcurrentHashMap<String, Long> LOCK_DTO_MAP = new ConcurrentHashMap<>();private static final ConcurrentHashMap<String, Semaphore> SEMAPHORE_MAP = new ConcurrentHashMap<>();private static final long TIMEOUT_DURATION = 60_000; // 60 secondspublic static boolean lock(String key) { Semaphore semaphore = SEMAPHORE_MAP.computeIfAbsent(key, k -> new Semaphore(1, true)); boolean acquired = false; try { // 1. 拿到许可证 acquired = semaphore.tryAcquire(1, TimeUnit.SECONDS); Preconditions.checkState(acquired, "获取锁超时: " + key); // 2. 现在互斥了,再操作被保护资源 Long old = LOCK_DTO_MAP.putIfAbsent(key, System.currentTimeMillis()); Preconditions.checkState(old == null, "Lock already held by this thread for key: " + key); return true; } catch (Exception ignored) { } finally { /* 4. 关键:只有真正拿到过许可的线程才需要“善后” */ if (acquired) { /* 4.1 判断是否超时,超时就当“没发生过”直接删记录 */ try { long holdTime = System.currentTimeMillis() - LOCK_DTO_MAP.get(key); if (holdTime > TIMEOUT_DURATION) { LOCK_DTO_MAP.remove(key); // 删记录" 超时,记录+许可证已清理" } } finally { semaphore.release(); // 还许可证 } } } return false;}/** 清空StripedLockUtils的所有数据 */public static void clearAppRestart() { for (String key : LOCK_DTO_MAP.keySet()) { StreamUtils.silentException( () -> { unlock(key); SEMAPHORE_MAP.remove(key); }); }}public static void unlock(String key) { StreamUtils.silentException(() -> LOCK_DTO_MAP.remove(key));} Neuer 251009-windows共享Win10-11设置无密码访问共享文件夹 Älter 250927-RPM查看安装软件和卸载软件(rpm -qa | grep mongodb-org)