Java - 从其他线程更改对象属性

时间:2016-09-27 13:56:48

标签: java multithreading network-programming

我正在编写简单的客户端 - 服务器程序。我面临的问题是:我正在从客户端向服务器发送一个对象,并为发送到服务器的每个对象启动新线程。

我需要从反序列化对象获取数据并使用此数据更新服务器对象属性。我怎么能这样做?

这是我的服务器代码:

...

// Property to be updated
private FieldMap fieldMap = new FieldMap();
public void startServer() {
    try {
        serverSocket.bind(new InetSocketAddress("localhost", port));
        (new Thread(this)).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void stopServer() {
    running = false;
    Thread.currentThread().interrupt();
}

@Override
public void run() {
    running = true;
    while (running) {
        try {
            this.setChanged();
            this.notifyObservers();
            System.out.println("Listening for a connection");
            Socket socket = serverSocket.accept();
            InputHandler inputHandler = new InputHandler(socket, fieldMap);
            (new Thread(inputHandler)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

...

这是侦听器对象代码:

public class InputHandler implements Runnable {

     private Socket socket;
     private ObjectInputStream objectInputStream;
     private FieldMap map;

     InputHandler(Socket socket, FieldMap map) throws IOException {
        this.socket = socket;
        objectInputStream = new ObjectInputStream(socket.getInputStream());
        this.map = map;
     }

    @Override
    public void run() {
        try {
            Lemming lemming = (Lemming) objectInputStream.readObject();
            lemming.getFieldMap().union(map);
            map = lemming.getFieldMap();
            System.out.println(lemming);
            (new Thread(lemming)).start();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                 objectInputStream.close();
                 socket.close();
            } catch (IOException e) {
                 e.printStackTrace();
            }
        }
    }
}

如何从fieldMap更新InputHandler

1 个答案:

答案 0 :(得分:0)

您需要一些方法,例如java.uitl.Map

fieldMap.clear()
fieldMap.putAll(otherFieldMap)