如何从某个Java线程调用方法

时间:2013-05-04 21:19:14

标签: java multithreading

目前我正在研究Java客户端/服务器聊天应用程序并得到一个问题,我将尽可能清楚地解释。

我的服务器部分不断为每个上线用户创建线程(new ServerThread):

while (isRunning) {
    Socket socket = serverSocket.accept();
    DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
    outputStreams.put(socket, dout);
    System.out.println (outputStreams.values());
    new ServerThread(this, socket); 
    window.newConnectionInfo(socket);// informace
}

我在 ServerThread 类中有一个getter方法,我想根据socket从某个 ServerThread 实例调用它。但 ServerThread 类未分配给任何变量,因此我不确切知道如何从中调用方法。对此有何解决方案?

1 个答案:

答案 0 :(得分:1)

很简单,你需要找到并找到你想要强制调用方法的线程,你要保留你创建的每个线程,我建议你使用你用来保持客户端的地图< ServerThread,DataOutputStream>,所以这里你现在拥有所有线程(和ServerThread中的Scoket实例),好的和答案。

好的,首先你需要一个在ServerThread中发信号通知目标线程的方法,比如这个

class ServerThread{
public void forceToCall(Object o){//an object argument, would be void too, or an interface
    //do something, call someone
  }
}
那么,那么谁会打电话给这个方法呢?只需创建一个可以调用目标客户端同步或异步模式的类,就像这样

class ClientMethodCaller implements Runnable{
     ServerThread st;Object arg
     public ClientMethodCaller(ServerThread st,Object arg){this.st=st;this.arg=arg;}
     public void run () {
        st.forceToCall(arg);//signalling the client async
     }
} 

最后,只要您希望客户端运行特定方法,在找到客户端(ServerThread)实例后,通过ClientMethodCaller调用目标方法

ServerThread st;//got the instance
new Thread(new ClientMethodCaller(st,"Hello!")).start();

最后一句话,这不好,为任何客户端登录运行一个线程,如果该程序不小,用户数量也很多。 同时检查this tutorial,也会有帮助

相关问题