Dmitry Avgustis
Dmitry Avgustis

Reputation: 1131

How to call a method from a certain Java thread

Currently I am working on Java client/server chat app and got one question, I'll try to explain as clear as possible.

My server part keeps creating threads (new ServerThread) for each user who comes online:

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
}

I have a getter method in a ServerThread class, which I want to call from the certain ServerThread instance based on socket. But ServerThread class isn't assigned to any variable, so I don't know exactly how to call methods from it. Any solution on that?

Upvotes: 1

Views: 1681

Answers (1)

user2511414
user2511414

Reputation:

Easy, you need to locate and find the thread you want to force call a method, that you would keeps every thread you create, I suggest you the Map you are using for keeping clients would be in < ServerThread ,DataOutputStream >, so here you have all threads now (and Scoket instance inside the ServerThread), okay and the answer.

okay first you need a method for signalling the target thread in the ServerThread, like this

class ServerThread{
public void forceToCall(Object o){//an object argument, would be void too, or an interface
    //do something, call someone
  }
}

then, so who is going to call this method? simply create a class that would call the target client sync or async mode, just like this

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
     }
} 

and at the end, whenever you want to a client to run a specific method, just after finding the client(ServerThread) instance, call the target method by ClientMethodCaller

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

and the final word, this is not good, running a thread for any client logins, IF the program, is not small and the number of users are to much. also check this tutorial too, would help

Upvotes: 1

Related Questions