根据key加锁执行

public class SyncKey {

    Map<String, ReentrantLock> muteCache = new ConcurrentHashMap<>();

    public void exec(String key, Runnable statement) {
        ReentrantLock mutex4Key = null, now;
        do {
            if (mutex4Key != null) {
                mutex4Key.unlock();
            }
            mutex4Key = muteCache.computeIfAbsent(key, k -> new ReentrantLock());
            mutex4Key.lock();
            now = muteCache.get(key);
        } while (now == null || now != mutex4Key);
        try {
            statement.run();
        } finally {
            if (mutex4Key.getQueueLength() == 0) {
                muteCache.remove(key);
            }
            mutex4Key.unlock();
        }
    }

//    public static class Test extends Thread {
//        @Override
//        public void run() {
//            Singleton.SINGLETON.sync.exec("key", () -> {
//                System.out.println("开始");
//                System.out.println("结束");
//            });
//        }
//
//        @AllArgsConstructor
//        public enum Singleton {
//            SINGLETON("syncKey", new SyncKey());
//            public String key;
//            public SyncKey sync;
//        }
//    }
//
//    public static void main(String[] args) {
//        for (int i = 0; i < 20000; i++) {
//            new Thread(new Test()).start();
//        }
//    }
}

posted @ 2022-02-07 16:17  脚下坚实  阅读(124)  评论(0)    收藏  举报