简体   繁体   English

Java线程 - 工作线程改变其老板的hashmap

[英]Java threading - worker threads changing hashmap of its boss

I have a class (Server) which listens for requests and once a request is made, starts a new thread which handles it. 我有一个类(Server)侦听请求,一旦发出请求,就会启动一个处理它的新线程。 The handler thread will read in the data, store it into a hashmap and finish. 处理程序线程将读入数据,将其存储到hashmap中并完成。 I have put the hashmap in the server class as there can be multiple handler threads reading in the data as and when it comes in. 我已经将hashmap放在服务器类中,因为当数据进入时,可以有多个处理程序线程读取数据。

I'm confused whether this is the correct approach as in order to alter/access the hashmap, I'd have to write getters & setters and pass in the Server class to each and every worker thread. 我很困惑这是否是正确的方法,因为为了更改/访问hashmap,我必须编写getter和setter并将Server类传递给每个工作线程。 Some example code to try and describe my query: 尝试描述我的查询的一些示例代码:

public class Server implements Runnable {
        private HashMap<String, Integer> data;

    public void run() {
       while(true) {
            Socket s = serverSocket.accept();
            Handler h = new Handler(s);
            Thread t = new Thread(h);
            t.start();
       }
   }
}

public class Handler implements Runnable {

    public void run() {
        //read in data from socket
        data.put(d); //access the hashmap and insert data in
    } 

}

Any advice would be much appreciated. 任何建议将不胜感激。 Thanks. 谢谢。

Your approach is fine, but you should either use a ConcurrentMap , or synchronize on the map. 您的方法很好,但您应该使用ConcurrentMap ,或者在地图上synchronize The first approach is better since synchronized collections are optimized in order to avoid blocking whenever it is possible. 第一种方法更好,因为同步集合已经过优化,以便在可能的情况下避免阻塞

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

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