消息传递到Java J2ME中的asynchronus工作线程

我正在研究J2ME蓝牙应用程序,其中一个类搜索其他蓝牙设备。 它在另一个线程中执行此操作,因此GUI不会冻结。

我遇到的问题是如何将消息传递给线程。 我可以要求它搜索或取消搜索,它可以告诉GUI它找到了其他一些设备。 目前我使用通知和等待,但这似乎是一个黑客。 我真正想要的是用参数调用notify的一些方法,例如我想要它做什么。 有没有办法做到这一点?

这种情况的一般方法必须如下:

  1. 使用“视图”将远程数据源去耦。
  2. 确保视图能够在基础数据更改时动态更新。 J2ME组件默认执行此操作 – 但如果您创建自己的组件,则必须考虑这一点。
  3. 运行单独的线程并检索数据。
  4. 每当数据到达时通知视图。

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

你必须实现自己的阻塞队列,这实际上是一个生产者 – 消费者问题。 一旦你有了一个阻塞队列,你就可以用他们自己的方法轻松地将推送包装到队列中,让你觉得你正在对工作线程进行异步调用。