高级农民
- 积分
- 2021
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-1-17
- 最后登录
- 1970-1-1
|
- public class ExpiringMap<K, V> extends TimerTask {
- // fields
- class Node<K, V> {
- // fields
- private K key;
- private V value;
- private long duration;
- private long startTime;
- // methods
- public Node (V value, long duration, long startTime) {
- this.value = value;
- this.duration = duration;
- this.startTime = startTime;
- }
- }
- private LinkedList<Node> list;
- HashMap<K, Node> map;
- public ExpiringMap(){
- map = new HashMap<>();
- list = new LinkedList<>();
- }
- public void put(K key, V value, long duration) {
- long startTime = System.currentTimeMillis();
- Node node = new Node(value, duration, startTime);
- map.put(key, node);
- checkTime();
- addToHead(value, duration, startTime);
- }
- public V get(K key) {
- checkTime();
- if (map.containsKey(key)) {
- Node node = map.get(key);
- return (V) node.value;
- } else {
- return null;
- }
- }
- public void checkTime() {
- long curTime = System.currentTimeMillis();
- while (!list.isEmpty()) {
- Node node = list.getLast();
- if (node.duration + node.startTime > curTime) {
- list.removeLast();
- map.remove(node.key);
- } else {
- break;
- }
- }
- }
- public void addToHead(V value, long duration, long startTime) {
- Node node = new Node(value, duration, startTime);
- list.addFirst(node);
- }
- @Override
- public void run() {
- checkTime();
- }
- public static void main(String[] args) {
- Timer timer = new Timer(true);
- ExpiringMap expiringMap = new ExpiringMap();
- timer.schedule(expiringMap,0,1000);//1000毫秒检查一次
- }
- }
复制代码
自己写了一下,我也不确定是否对,所以贴一下大家找找错。
问一下多线程那个楼主当时写了吗,应该是只说思路吧??写感觉太复杂了。。。 |
|