如何使我的哈希映射在Java中变为公开,以便可以从任何地方进行打印?

huangapple go评论91阅读模式
英文:

How can I make my hashmap public to be printed from anywhere in java?

问题

我想能够在一个线程方法内打印一个哈希映射(hashmap),但是我无法弄清楚如何使其成为全局变量,或者如何将哈希映射作为参数传递给函数。有人能帮我解决这个问题吗?
我认为我的问题可能是,也许我是从一个文件中处理所有事情?像这样从一个文件中实现我需要的功能是可能的吗?

谢谢。

import java.util.Scanner;
import java.util.HashMap;
import java.net.*;
import java.io.*;
import java.lang.Thread;

public class Server{
    
    public static void main(String[] args){

    if (args.length < 1) return;

    HashMap<String, String> Distances = new HashMap<String, String>(); // 这里是映射
    
    menu mThread = new menu(Distances); // 将映射传递给menu线程

    try{ 
        InetAddress ip = InetAddress.getLocalHost();
        Distances.put(ip.toString(), "0");
        System.out.println(Distances);
    } catch (UnknownHostException e){
        e.printStackTrace();
    }

    
    int port = Integer.parseInt(args[0]); 
    
    try (ServerSocket serverSocket = new ServerSocket(port)) {
        System.out.println("server is listening on port " + port);

        while(true){
            Socket socket = serverSocket.accept();
            System.out.println("Client connected");	     
            serverSocket.close();
            System.exit(0);
        }
    } catch(IOException ex) {
        System.out.println("exception");
        ex.printStackTrace();
    }

    }
}
class menu implements Runnable{
    HashMap<String, String> Distances; // 存储传递的映射
    
    menu(HashMap<String, String> distances){
        Distances = distances; // 初始化映射
        Thread m = new Thread(this);
        m.start(); // 使用start方法来启动线程
    }
    
    public void run(){
        printMenu();
    }
    public void printMenu(){
        
        Scanner input = new Scanner(System.in);
        int choice = 0; // 初始化choice
        System.out.println("1. help\n 2. routing\n 3. myPort");
        while(choice != 4){
            choice = input.nextInt();
            if (choice == 1)
                System.out.println("control c to quit, otherwise make another selection");
            else if (choice == 2)
                System.out.println(Distances); // 这里是问题所在

        }	
    }
}
英文:

I want to be able to print a hashmap inside a threaded method, but I can't figure out how to make it global or how to pass the hashmap as a parameter to the function. Could someone help me with this please?
I think my problem is that, maybe, I am doing everything from one file? Is it possible to do what I need from one file like this?

Thank you.

import java.util.Scanner;
import java.util.HashMap;
import java.net.*;
import java.io.*;
import java.lang.Thread;
public class Server{
public static void main(String[] args){
if (args.length &lt; 1) return;
HashMap&lt;String, String&gt; Distances = new HashMap&lt;String, String&gt;(); // here&#39;s the map
menu mThread = new menu();
try{ 
InetAddress ip = InetAddress.getLocalHost();
Distances.put(ip.toString(), &quot;0&quot;);
System.out.println(Distances);
} catch (UnknownHostException e){
e.printStackTrace();
}
int port = Integer.parseInt(args[0]); 
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println(&quot;server is listening on port &quot; + port);
while(true){
Socket socket = serverSocket.accept();
System.out.println(&quot;Client connected&quot;);	     
serverSocket.close();
System.exit(0);
}
} catch(IOException ex) {
System.out.println(&quot;exception&quot;);
ex.printStackTrace();
}
}
}
class menu implements Runnable{
menu(){
Thread m = new Thread(this);
m.run();
}
public void run(){
printMenu();
}
public void printMenu(){
Scanner input = new Scanner(System.in);
int choice;
System.out.println(&quot;1. help\n 2. routing\n 3. myPort&quot;);
while(choice != 4){
choice = input.nextInt();
if (choice == 1)
System.out.println(&quot;control c to quit, otherwise make another selection&quot;);
else if (choice == 2)
System.out.println(Distances); // here is the issue
}	
}
}

答案1

得分: 1

首先,您应该知道 HashMap 不是线程安全的,因此最好使用 ConcurrentHashMap。实现所需行为的一种方法是创建一个类,该类将接受一个地图作为构造函数参数,这样您就可以在运行方法中传递并使用它。然后,您需要将该类的实例传递给线程。这里有一个非常简单的示例 - https://intellipaat.com/community/24428/how-can-i-pass-a-parameter-to-a-java-thread

英文:

Firstly, you should know that HashMap isn't thread safe, so it would be better to use ConcurentHashMap. One of the way to implement desired behaviour is to create a class that would accept a map as constructor parameter, so you will be able to pass it and use it a run method. Then you have to pass instance of the class to the Thread. Here's a really simple example - https://intellipaat.com/community/24428/how-can-i-pass-a-parameter-to-a-java-thread.

huangapple
  • 本文由 发表于 2020年9月22日 09:13:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64001788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定