我正在研究J2ME蓝牙应用程序,其中一个类搜索其他蓝牙设备。它在另一个线程中执行此操作,因此GUI不会冻结。将消息传递给Java中的asynchronus工作线程J2ME
我遇到的问题是如何将消息传递给线程。我可以要求它搜索或取消搜索,并且它可以告诉GUI找到了其他一些设备。目前我使用通知和等待,但这似乎是一个黑客。我真正想要的是用参数调用notify的某种方式,例如我希望它执行的操作。有没有办法做到这一点?
我正在研究J2ME蓝牙应用程序,其中一个类搜索其他蓝牙设备。它在另一个线程中执行此操作,因此GUI不会冻结。将消息传递给Java中的asynchronus工作线程J2ME
我遇到的问题是如何将消息传递给线程。我可以要求它搜索或取消搜索,并且它可以告诉GUI找到了其他一些设备。目前我使用通知和等待,但这似乎是一个黑客。我真正想要的是用参数调用notify的某种方式,例如我希望它执行的操作。有没有办法做到这一点?
的一般方法这种情况必须如下:
MIDlet的工作代码下面贴
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.*;
public class AsyncUI extends MIDlet implements SearchListener, CommandListener{
Command CANCEL = new Command("STOP SEARCH",Command.CANCEL,1);
Command EXIT = new Command("EXIT",Command.EXIT,2);
SearchDevices finder = new SearchDevices();
List deviceList = new List("List of Devices",List.IMPLICIT);
public void startApp() {
Display d = Display.getDisplay(this);
finder.setSearchListener(this);
deviceList.addCommand(CANCEL);
deviceList.addCommand(EXIT);
deviceList.setCommandListener(this);
d.setCurrent(deviceList);
new Thread(finder).start();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void found(Device d){
deviceList.append(d.getName(), null);
}
public void commandAction(Command c, Displayable d){
if(c == CANCEL){
finder.cancel();
deviceList.removeCommand(CANCEL);
}else if(c== EXIT){
finder.cancel(); /* Cleanup all resources before you quit*/
notifyDestroyed();
}
}
}
class SearchDevices implements Runnable{
private boolean keepFinding=true;
private static final int LONG_TIME=10000; /* 10 Seconds */
SearchListener l =null; /* Currently only one listener. There could be many*/
public void run(){
int i =0;
System.out.println(" -- Started the activity of finding --");
while(keepFinding){
try {
Thread.currentThread().sleep(LONG_TIME);
Device d = new Device("Device Found "+i);
i++;
System.out.println(" -- Found the device --");
l.found(d);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println(" -- No more devices will be found --");
}
public void cancel(){ keepFinding = false; }
public void setSearchListener(SearchListener l){this.l=l;}
}
class Device{
String name;
public Device(String name){ this.name = name; }
public String getName(){ return name ; }
}
interface SearchListener{
public void found(Device device);
}
你必须执行你自己的阻塞队列,这实际上是一个producer-consumer问题。一旦你有了一个阻塞队列,你就可以轻松地将它们推送到它们自己的方法中的队列中,让你觉得你正在对工作线程进行异步调用。
你可以发布你正在尝试做的任何代码片段? – Ram 2009-08-05 08:29:17