目前我正在开发 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 方法,我想从基于套接字的特定 ServerThread 实例调用该方法。但是 ServerThread 类没有分配给任何变量,所以我不知道如何从中调用方法。有什么解决办法吗?
最佳答案
很简单,您需要定位并找到要强制调用方法的线程,您将保留您创建的每个线程,我建议您用于保留客户端的 Map 将位于 < 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也会有帮助
关于java - 如何从某个Java线程调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379067/