gpt4 book ai didi

java - 如何让ScheduleTask在某个时间执行一次任务?

转载 作者:行者123 更新时间:2023-11-30 05:48:16 24 4
gpt4 key购买 nike

最近在使用ScheduleTask,有这样的问题。我希望本地图大小超过 MAX_SIZE 字段时,我的 ScheduleTask 每 5 秒从 map 中删除元素。我正在尝试这样做:

public class RemoverThread extends TimerTask {

private AbstractCustomCache customCache;
private static final int MAX_SIZE = 2;

public RemoverThread(AbstractCustomCache customCache) {
this.customCache = customCache;
}

@Override
public void run() {
if (customCache.getCacheEntry().size() > MAX_SIZE) {
List<String> gg = new ArrayList<>(customCache.getCacheEntry().keySet());
for (String s : gg) {
System.out.println("Element was remove: " + customCache.getCacheEntry().remove(s));
System.out.println("Time: " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()));
if (customCache.getCacheEntry().size() <= MAX_SIZE) {
break;
}
}
}
}
}

我的主要:

public class Main {
public static void main(String[] args) {
AbstractCustomCacheStatistics gh = new MapCacheStatistics();
AbstractCustomCache gg = new MapCache(gh);


for (int i = 0; i < 5; i++){
gg.put("ab" + i);
}
RemoverThread removerThread = new RemoverThread(gg);
Executors.newScheduledThreadPool(2).scheduleAtFixedRate(removerThread, 5, 5, TimeUnit.SECONDS);

for (int i = 0; i < 3; i++){
gg.put("abc" + i);
}
}
}

抽象自定义缓存:

public abstract class AbstractCustomCache implements CustomCache{

private Map<String, CacheEntry> cacheEntry = new LinkedHashMap<>();

public Map<String, CacheEntry> getCacheEntry() {
return Collections.synchronizedMap(cacheEntry);
}
}

我的输出中有这样的内容:

Element was remove: CacheEntry{field='ab0'}
Time: 2019/01/31 11:39:11
Element was remove: CacheEntry{field='ab1'}
Time: 2019/01/31 11:39:11
Element was remove: CacheEntry{field='ab2'}
Time: 2019/01/31 11:39:11
Element was remove: CacheEntry{field='ab3'}
Time: 2019/01/31 11:39:11
Element was remove: CacheEntry{field='ab4'}
Time: 2019/01/31 11:39:11
Element was remove: CacheEntry{field='abc0'}
Time: 2019/01/31 11:39:11

我做错了什么?可以怎样改进呢?我想从 map 上删除每 5 秒发生一次的事件。例如,我添加了ab0、ab1、ab2、ab3、ab4。该流应删除 ab0、ab1、ab2。由于 map 中的元素大于 MAX_SIZE。然后我添加abc0、abc1、abc2。删除第一个元素 5 秒后,ab3, ab4, abc0 应被删除。但是,正如您所看到的,所有项目都会同时删除。

最佳答案

What am I doing wrong?

  1. 使用Executors.newScheduledThreadPool(2).scheduleAtFixedRate(removerThread, 5, 5, TimeUnit.SECONDS);,第一次执行时间将为 delayed5秒时,此时缓存包含:ab0 ab1 ab2 ab3 ab4 abc0 abc1 ab2,前5个将被删除。

  2. 您需要一个线程安全版本 AbstractCustomCache customCache,因为它是由多个线程修改的。

关于java - 如何让ScheduleTask在某个时间执行一次任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54457414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com