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存储,然后开启定时器,进行定时移除房间满的人。



