[英]How to make ScheduleTask perform a task once at a certain time?
最近與 ScheduleTask 合作,我有這樣一個問題。 MAX_SIZE
圖大小超過MAX_SIZE
字段時,我希望我的 ScheduleTask 每 5 秒從我的地圖中刪除元素。 我正在嘗試這樣做:
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
我究竟做錯了什么? 如何改進? 我想從地圖中刪除每 5 秒發生一次。 例如,我添加了ab0, ab1, ab2, ab3, ab4
。 流應該刪除ab0, ab1, ab2
。 由於地圖中的元素大於MAX_SIZE
。 然后我添加abc0, abc1, abc2
。 刪除第一個元素后 5 秒ab3, ab4, abc0
應刪除ab3, ab4, abc0
。 但是,正如您所看到的,所有項目都被同時刪除。
我究竟做錯了什么?
與Executors.newScheduledThreadPool(2).scheduleAtFixedRate(removerThread, 5, 5, TimeUnit.SECONDS);
,第一次執行時間會延遲5
秒,此時緩存包含: ab0 ab1 ab2 ab3 ab4 abc0 abc1 ab2
,前5個將被刪除。
您需要一個線程安全版本AbstractCustomCache customCache
因為它被多個線程修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.