如何在一个类中处理多个线程? [英] How to deal with multiple threads in one class?

查看:134
本文介绍了如何在一个类中处理多个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线程通常以两种方式设计(参见java教程):通过扩展Thread类或实现Runnable类。无论哪种方式,您都需要指定在线程内运行的内容。

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.

我设计了一个类,一个针对在线资源的适配器,可以检索不同类型的信息。该类由getInformationOfTypeA()和getInformationOfTypeB()等方法组成。两者都包含连接到在线资源的代码,因此需要进行线程化以避免死锁。

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:我正在j2me中开发我的应用程序

更新:

感谢您的回复我认为最适合使用以下方法作为方法:

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

您如何看待这一点:

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();
    }
}

您如何看待这个?

推荐答案

听起来你应该有两个不同的类: InformationOfTypeAFetcher InformationOfTypeBFetcher ,每个都应该实现 Runnable 。他们每个人都可以引用你的 OnlineResourceAdapter (或类似的东西)的实例,但如果他们做不同的事情,他们应该是不同的类。

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.

这篇关于如何在一个类中处理多个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆