Sign in to follow this  
CodeMachine

[java] Multiple threads issue

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 {
 Thread m_threadSend = null;
 Thread m_threadReceive = null;
 
 public NetworkServer() {
 }
 
 public void start() {
  m_threadSend = new Thread(this);
  m_threadReceive = new Thread(this);

  m_threadSend.start();
  m_threadReceive.start();
 }
 
 public void stop() {
  m_threadSend.stop();
  m_threadSend.stop();
 }
 
 public void run() {
  while(true) {
   if(Thread.currentThread()==m_threadSend) {
    // Send messages from queue.
   } else {
    // Listen for incoming messages.
   }
  }
 }
}


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

Share this post


Link to post
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:

public void start() {
m_threadSend = new Thread(this);
m_threadReceive = new Thread(this);
}


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)
m_threadReceive should be NetowrkInput class (...)


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]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this