【发布时间】:2010-01-17 16:51:30
【问题描述】:
线程通常以两种方式设计(see java tutorials):通过扩展 Thread 类或通过实现 Runnable 类。无论哪种方式,您都需要指定将在线程内运行的内容。
我设计了一个类,一个针对在线资源的适配器,用于检索不同类型的信息。此类由 getInformationOfTypeA() 和 getInformationOfTypeB() 等方法组成。两者都包含连接在线资源的代码,因此都需要线程化以避免死锁。
问题是:我应该如何设计这个?我可以像下面那样做,但是我只能实现一种方法:
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
}
}
另一种方法是为每个方法创建单独的类,但这对我来说似乎不自然。
顺便说一句:我正在 j2me 中开发我的应用程序
更新:
感谢您的回复,我认为最适合使用以下方法作为方法:
你怎么看:
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();
}
}
你怎么看?
【问题讨论】:
标签: java multithreading java-me