You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java:实现每秒为HashMap中Timmy对应整数递增,达标后执行迁移

实现基于定时递增值的HashMap键迁移方案

嘿,这个需求挺有意思的!我来帮你拆解实现思路和完整代码,完美匹配你要的Timmy键递增、阈值迁移的逻辑:

1. 先搞定作为HashMap键的Timmy类

自定义对象要作为HashMap的键,必须重写equals()和hashCode()——不然HashMap会把同一个Timmy实例当成不同的键,导致操作失效。这里给你写个极简示例:

import java.util.Objects;

class Timmy {
    private String name;

    public Timmy(String name) {
        this.name = name;
    }

    // 重写equals,确保同名Timmy被识别为同一个键
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Timmy timmy = (Timmy) o;
        return Objects.equals(name, timmy.name);
    }

    // 重写hashCode,和equals逻辑保持一致(必须操作相同的字段)
    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public String toString() {
        return "Timmy{name='" + name + "'}";
    }
}

2. 核心实现:定时递增+多Map迁移逻辑

我用ScheduledExecutorService来做每秒定时任务(比传统Timer更稳定,支持线程池管理),同时维护一个Map列表来处理多轮迁移需求:

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimmyMapMigration {
    public static void main(String[] args) {
        // 初始化多个HashMap,组成迁移链(想加多少就加多少)
        Map<Timmy, Integer> map1 = new HashMap<>();
        Map<Timmy, Integer> map2 = new HashMap<>();
        Map<Timmy, Integer> map3 = new HashMap<>();
        List<Map<Timmy, Integer>> mapMigrationChain = List.of(map1, map2, map3);

        // 创建Timmy实例作为键
        Timmy timmy = new Timmy("Timmy");
        // 初始把Timmy放到第一个Map,值从0开始
        map1.put(timmy, 0);

        // 记录Timmy当前所在的Map索引
        int currentMapIndex = 0;
        // 定义迁移阈值
        final int MIGRATION_THRESHOLD = 400;

        // 创建单线程定时任务池,每秒执行一次递增逻辑
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(() -> {
            Map<Timmy, Integer> currentMap = mapMigrationChain.get(currentMapIndex);
            
            // 获取当前值并递增
            Integer currentValue = currentMap.get(timmy);
            if (currentValue == null) return; // 理论上不会触发,做个兜底
            int newValue = currentValue + 1;
            currentMap.put(timmy, newValue);
            System.out.printf("当前Map[%d]中Timmy的值:%d%n", currentMapIndex, newValue);

            // 检查是否达到迁移条件
            if (newValue >= MIGRATION_THRESHOLD) {
                if (currentMapIndex < mapMigrationChain.size() - 1) {
                    // 从当前Map移除Timmy,移到下一个Map
                    currentMap.remove(timmy);
                    currentMapIndex++;
                    // 这里可以选择重置值为0,或者保留400继续递增,按需修改
                    mapMigrationChain.get(currentMapIndex).put(timmy, 0);
                    System.out.printf("Timmy已迁移到Map[%d],值重置为0%n", currentMapIndex);
                } else {
                    // 已经是最后一个Map,停止定时任务
                    executor.shutdown();
                    System.out.println("Timmy已到达最后一个Map,定时任务停止");
                }
            }
        }, 0, 1, TimeUnit.SECONDS); // 初始延迟0秒,每秒执行一次
    }
}

3. 关键细节说明

  • 定时任务选型:用ScheduledExecutorService而非Timer,因为Timer在任务抛出异常时会直接停掉整个定时器,线程池的方式容错性更强。
  • 迁移逻辑灵活调整:如果需要迁移后继续从400往上递增,只需要把put(timmy, 0)改成put(timmy, newValue)就行。
  • 线程安全注意:如果是多线程环境下使用,建议把普通HashMap换成ConcurrentHashMap,或者手动加synchronized锁,避免并发修改异常。上面的示例是单线程定时任务,用普通HashMap完全没问题。
  • 扩展迁移链:只要在mapMigrationChain列表里添加更多HashMap,就能支持无限次迁移,逻辑会自动处理。

内容的提问来源于stack exchange,提问作者Shaden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:56:50