How to deal with multiple threads in one class?

hsmit picture hsmit · Jan 17, 2010 · Viewed 22.4k times · Source

Threads are often designed in two ways (see java tutorials): either by extending the Thread class or by implementing the Runnable class. Either way, you need to specify what will run inside the thread.

I designed a class, an adapter towards an online resource, that retrieves different kinds of information. This class consists of methods like getInformationOfTypeA() and getInformationOfTypeB(). Both contain code to connect to online resources, so both need to be threaded to avoid deadlocks.

The question is: how should I design this? I can do it like below, but then I can only implement one method:

public class OnlineResourceAdapter implements Runnable {

  public void run() {
      //get stuff from resource
      getInformationOfTypeA();
  }

  public static void main(String args[]) {
      (new Thread(new OnlineResourceAdapter ())).start();
  }

  public void getInformationOfTypeA(){
      //get information of type A
  }

  public void getInformationOfTypeB(){
      //get information of type B
  }

}

Another way would be by creating separate classes for each method, but that seems unnatural to me.

Btw: I'm developing my application in j2me

UPDATE:

Thanks to your responses I think it is most suiting to use something like the following as methods:

What do you think of this:

public class OnlineResourceAdapter{
    public void getInformationOfTypeA(){
        Thread t = new Thread(new Runnable() {           
            public void run() { 
                //do stuff here
            } 
        });
        t.start();
    }

    public void getInformationOfTypeB(){
        Thread t = new Thread(new Runnable() {           
            public void run() { 
                //do stuff here
            } 
        });
        t.start();
    }
}

What do you think of this?

Answer

Jon Skeet picture Jon Skeet · Jan 17, 2010

It sounds to me like you should actually have two different classes: InformationOfTypeAFetcher and InformationOfTypeBFetcher, each of which should implement Runnable. Each of them may have a reference to an instance of your OnlineResourceAdapter (or something similar) but if they're doing different things, they should be different classes.