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

如何让Thread构造函数从LinkedHashMap中获取参数?

Alright, let's tackle this problem step by step. You're building a Gossip protocol simulation with Java threads, and need to feed data from your LinkedHashMap<String, String> (node-to-neighbors mapping) into your Thread constructors. Here's how to do it cleanly:

Step 1: Create a Custom Gossip Thread Class

Instead of using the raw Thread class directly, define a custom thread class that accepts the data it needs via its constructor. This makes it easy to pass in the node ID and its neighbors from your map. I'll use the Runnable approach here since it's more flexible for reuse.

import java.util.List;

public class GossipNode implements Runnable {
    private final String nodeId;
    private final List<String> neighbors;
    // Optional: Pass the entire map if your logic needs to access other nodes' data
    // private final LinkedHashMap<String, String> allNodes;

    // Constructor that takes node-specific data
    public GossipNode(String nodeId, List<String> neighbors) {
        this.nodeId = nodeId;
        this.neighbors = neighbors;
    }

    @Override
    public void run() {
        // Your Gossip protocol logic goes here
        System.out.printf("Node %s starting gossip cycle with neighbors: %s%n", nodeId, neighbors);
        // Example: Periodically pick a random neighbor to push gossip data to
        // ... add your message propagation, state sync logic here ...
    }
}
Step 2: Parse the LinkedHashMap & Initialize Threads

Once you've loaded your adjacency list into the LinkedHashMap, iterate over each entry to create a GossipNode instance for every node. You'll just need to split the comma-separated neighbor string into a usable list first.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

public class GossipSimulation {
    public static void main(String[] args) {
        LinkedHashMap<String, String> nodeNeighborsMap = new LinkedHashMap<>();
        String filePath = "your_adjacency_list.txt";

        // Step 1: Read and parse the adjacency list file
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // Split line into node ID and neighbors (format: "1:2,4,6")
                String[] lineParts = line.split(":");
                if (lineParts.length == 2) {
                    String nodeId = lineParts[0].trim();
                    String neighborsStr = lineParts[1].trim();
                    nodeNeighborsMap.put(nodeId, neighborsStr);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading adjacency list file: " + e.getMessage());
            e.printStackTrace();
        }

        // Step 2: Spin up a thread for each node
        for (var entry : nodeNeighborsMap.entrySet()) {
            String nodeId = entry.getKey();
            String neighborsStr = entry.getValue();
            // Convert comma-separated string to a list of neighbor IDs
            List<String> neighbors = Arrays.asList(neighborsStr.split(","));
            
            // Initialize thread with node data from the map
            Thread gossipThread = new Thread(new GossipNode(nodeId, neighbors));
            gossipThread.start();
        }
    }
}
Key Tips for Your Simulation
  • Thread Safety: If multiple nodes will modify shared state (like a global gossip data store), use synchronized blocks or thread-safe collections (e.g., ConcurrentHashMap) to avoid race conditions.
  • Expandability: If your Gossip logic needs to reference the full node map (e.g., to validate neighbor IDs), add the LinkedHashMap as an extra parameter to the GossipNode constructor.
  • Error Handling: I added basic file reading error handling, but you might want to add checks for invalid line formats or empty neighbor lists.

This setup ensures each thread gets exactly the data it needs from your LinkedHashMap at initialization, keeping your simulation organized and easy to tweak as you build out the Gossip logic.

内容的提问来源于stack exchange,提问作者mr.Hamilton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:42:19