map移除數據時,不能使用迭代器 ,需如下寫法

  public void deleteCache(String key){
         Set<String> setKeys = map.keySet();
         //做移除時不能使用迭代器 ,需如下寫法
         Object[] keys = setKeys.toArray();
         for (int i = 0; i < keys.length; i++) {
             Cache value = map.get(keys[i]);
             System.out.println(" 當前移除數據:\t"+ value);
             map.remove(keys[i]);
         }


         for(Map.Entry<String, Cache> entry : map.entrySet()){
             Cache cache = entry.getValue();
             System.out.println(cache);
        }
    }

 

定時器線程移除數據

public class Xc {
    public static void main(String[] args) {
         CacheManage cacheManage = new CacheManage();
         for(int i=1;i<6;i++){
             cacheManage.put("json"+i, "劉小明"+i,i*1000L);
         }
         Map<String, Cache> map = cacheManage.map;
         for(Map.Entry<String, Cache> entry : map.entrySet()){
             Cache cache = entry.getValue();
             System.out.println(cache);
        }
         ScheduledExecutorService nst = Executors.newScheduledThreadPool(5);//5個定長定時器線程
        nst.scheduleAtFixedRate(new Runnable() {
            
            @Override
            public void run() {
                System.out.println("---"+Thread.currentThread().getName());
                cacheManage.checkValidityData();
            }
        }, 1, 2, TimeUnit.SECONDS);//延時1秒後執行,每2秒鐘執行一次從線程池拿的線程
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         for(int i=1;i<6;i++){
             System.out.println("---->");
             System.out.println(map.get("json"+i));
         }
    }
    
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章