简体   繁体   English

如何发送哈希图运行方法?

[英]how to send hash maps to run method?

I am writting java client and server in which I want to maintain hash map between multiple threads.I have written following code but I am unnable to access updated code in run method.Also are concurrent hash maps more useful in such scenario? 我正在编写要在多个线程之间维护哈希映射的Java客户端和服务器。我编写了以下代码,但无法在run方法中访问更新的代码。在这种情况下,并发哈希映射是否更有用? Any tips will be very helpful.Thanks in advance 任何提示将非常有帮助。

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;


public class JavaServer extends Thread{

    //To access packet in run method
    static byte[] receiveData=new byte[2048];
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
            receiveData.length);
    JavaGenericCryptoLibrary cryptoObj=new JavaGenericCryptoLibrary();
    static JavaBuisinessFunctionsServer objB=new JavaBuisinessFunctionsServer();
    static DatagramSocket ds;
    static Map<String,String>  hm = new HashMap<String,String>();
    public JavaServer(DatagramSocket ds, Map<String,String> hm1) {
        JavaServer.ds=ds;
        JavaServer.hm=hm1;
    }


    public static void main(String[] args)
    {
        @SuppressWarnings("unused")
        JSONObject receivedObj = null;
        try {
            // Port Number for login
            int serverPort_login = 3964;
            int serverPort_requests = 3764;

            DatagramSocket serverSocket = new DatagramSocket(serverPort_login);
            DatagramSocket serverSocket_clients = new DatagramSocket(serverPort_requests);
            DatagramPacket receivePacket = new DatagramPacket(receiveData,
                    receiveData.length);

            hm.put("Current_User","Blank");
            // Server initialized
            System.out.println("Intilized Server");
            while(true)
            {   
                hm.remove("Current_User");
                hm.put("Current_User","Blank");
                serverSocket.receive(receivePacket);
                hm=(HashMap<String, String>) objB.login(serverSocket,receivePacket.getAddress(),receivePacket.getPort(),(HashMap<String, String>) hm);
                System.out.println("current user at server"+hm.get("Current_User"));
                //JavaServer r = new JavaServer(serverSocket_clients,hm);
                System.out.println("before thread:"+JavaServer.hm.get("Current_User"));
                System.out.println("before thread:"+JavaServer.hm.get(JavaServer.hm.get("Current_User")));

                new JavaServer(serverSocket_clients, hm).start();
            }
        } catch (Exception e) {
            System.out.println("Server" + e);
        } 
    }

    @SuppressWarnings("unchecked")
    public void run()
    {
        try {
            // Packet received on the thread.
            // Respective function will be initialized 
            JSONObject online_user_json_obj=new JSONObject();
            while(true)
            {   
                ds.receive(receivePacket);
                JSONObject t=cryptoObj.readRecievedPacket(receivePacket);
                switch((String)t.get("Command"))
                {
                case "Chat":

                    break;
                case "Logout":

                    break;
                case "List":

                    Enumeration<String> online_users = cryptoObj.get_Online_Users();
                    online_user_json_obj.put("List", online_users);
                    String user=hm.get("Current_User");
                    System.out.println("user "+user);
                    String ip_port=hm.get(user);
                    System.out.println("ip_port"+ip_port);
                                    //Here I amnot getting updated values
                    String[] ip_port_arr=ip_port.split(" ");
                    System.out.println(ip_port_arr[0]);
                    InetAddress ia=InetAddress.getByName(ip_port_arr[0]);
                    int port=Integer.getInteger(ip_port_arr[1]);
                    ds.send(cryptoObj.udpPacketGenerator(online_user_json_obj,ia,port));
                    break;
                default:
                    System.out.println("Rogue Data");
                    break;
                }

            } 
        }catch (Exception e) {
            e.printStackTrace();
        }   

    }
}

I think you need to look at a book like Lea's Concurrent Programming in Java. 我认为您需要看一本书,例如Lea的Java并行编程。 One thread needs to become the object's monitor. 一个线程需要成为对象的监视器。 Then all the servers can call a wait() on the HashMap and be woken up after the monitor is notify(). 然后,所有服务器都可以在HashMap上调用wait(),并在监视器是notify()之后被唤醒。 You then call notifyAll() from the HashMap's monitor thread when the HashMap is modified. 然后,当修改HashMap时,您可以从HashMap的监视线程中调用notifyAll()。 See java.lang.Object notify(), wait() and notifyAll() for information on how to set this up. 有关如何进行设置的信息,请参见java.lang.Object notify(),wait()和notifyAll()。

Basically, you'll have to designate one thread the monitor of the object. 基本上,您必须指定一个线程来监视对象的监视器。 Then, when that thread is woken by notify() you'll notify all the other threads. 然后,当该线程被notify()唤醒时,您将通知所有其他线程。

ConcurrentHashMap will be helpful in your case. ConcurrentHashMap将对您的情况有所帮助。 Else you can use a lock and guard the access to the hashMap that way, the changes will be visible to all threads. 否则,您可以使用锁并以这种方式保护对hashMap的访问,更改将对所有线程可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM