chm使用 1.removeIf之 满足某个条件,则移除指定的key 2.使用场景是匹配队列中满4人开赛

chm使用 1.removeIf之 满足某个条件,则移除指定的key 2.使用场景是匹配队列中满4人开赛,第1张

chm使用 1.removeIf之 满足某个条件,则移除指定的key 2.使用场景是匹配队列中满4人开赛
package org.example.testremoveif;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        Map map = new ConcurrentHashMap<>();
        map.put(1, "1");
        map.put(2, "2");
        map.put(55, "55");
        map.put(3, "3");
        map.put(4, "4");

        ScheduledExecutorService schedule = Executors.newScheduledThreadPool(5);
        schedule.scheduleAtFixedRate(() -> {
            // 满足条件,则移除
            map.entrySet().removeIf(entry -> {
                Integer key = entry.getKey();
                String value = entry.getValue();
                if (key < 4) {
                    System.out.println("移除key=" + key + " value=" + value + "剩余:" + map.size() + "  " + Thread.currentThread().getName());
                    return true;
                }

                System.out.println(key + " value=" + value + "剩余:" + map.size() + "  " + Thread.currentThread().getName());
                return false;
            });
        }, 1, 1, TimeUnit.SECONDS);
    }
}

使用场景:

如:匹配中,value是一个Room,则满4人开启一个房间。则匹配队列就可以使用这个Chm存储,然后开启定时器,进行定时移除房间满的人。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4015262.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-22
下一篇 2022-10-22

发表评论

登录后才能评论

评论列表(0条)

保存