Recommended Posts

CodeMachine    100
Hi again I have some thread problem. I have a class "NetworkServer" that should listen for incoming messages and also be able to send messages over ObjectInputStream/ObjectOutputStream. Right know I only have the listening part threaded. Now I want the sender part to be threaded as well in the same class. Now I extend the "Thread" class. But now I need to implement "Runnable" instead when having TWO threads, I think? Is this the way to do it (kind of)??
public class NetworkServer implements Runnable {

public NetworkServer() {
}

public void start() {

}

public void stop() {
}

public void run() {
while(true) {
// Send messages from queue.
} else {
// Listen for incoming messages.
}
}
}
}


Kind regards [Edited by - CodeMachine on November 8, 2006 10:14:21 AM]

Share on other sites
smc    292
I would suggest creating three separate source files and thus classes. For example I would create:

NetworkServer - Creates and Manages Network Services
NetworkInput - Handles Network Input
NetowrkOutput - Handles Network Output

The Network Input and Output classes would extend Thread or implement Runnable.

If you must keep it in the same class, then use inner classes. The above structure will be the same. Just the IO classes will be inner classes to NetworkServer.

Quote:

This makes no sense. If you were to do this, then you will have two threads executing the run() method of NetworkServer.

m_threadSend should be NetworkOutput class (inner or otherwize)

As a side note. I alway use the Runnable interface unless I need tighter coupling between the class and the thread. Otherwize I use the Runnable interface as this leaves open the possibility to still class inheritance. You can always have the class implementing the Runnable interface manage it's own thread. i.e.

NetworkOutput.init() - Init resources
NetworkOutput.start() - Start thread and network output
NetworkOutput.stop() - Stop thread and network output
NetworkOutput.destory() - clean up

[Edited by - smc on November 8, 2006 8:14:19 PM]

Create an account

Register a new account