我在調製器中使用我的「Producer-Mediator-Consumer」模型中有一個LinkedBlockingQueue
。生產者首先更新添加到activityQueue中的Mediator。接下來,消費者/活動在隊列上等待/收聽並抓取下一個項目。從隊列中更新活動的最佳方法
我想要一個活動來查看隊列大小已更改,並抓住下一個項目。 調解員無法看到活動只有活動可以看到調解員。那麼,如何創建我想要的偵聽器機制?
這裏是我的調解器類,它包含隊列,活動將以某種方式查看隊列並獲知是否需要更新。進入隊列中的數據可能有點雜亂,因此輪詢機制無法工作。
public class MediatorData {
/** Queue for the Activity */
LinkedBlockingQueue <byte[]> queueConsumer = new LinkedBlockingQueue <byte[]>();
/**
* Add data to a queue(s) for consumption
*/
public void put(byte[] data) throws InterruptedException {
queueConsumer.add(data);
}
/**
* Return data from the queue for the Feature calculations
*/
public byte[] getFeatureData() throws InterruptedException {
return queueConsumer.poll(100, TimeUnit.MILLISECONDS);
}
}
我的活動類的示例,它的圖形類,因此隊列偵聽器必須高效快速。
public class DisplayGraph extends Activity {
// populated from Application Class where its created
pirvate MediatorData md;
public void onCreate(Bundle savedInstanceState) {
md = getMediator(); // This comes from the custom Application class
... some type of listener to queue
}
private void getQueueData() {
byte[] tv = md.queueConsumer.poll();
// can't update textview get exception CalledFromWrongThreadException
((TextView) DisplayGraph.this.findViewById(R.id.tv)).setText("TV " + tv[0]);
}
}
我發佈了一些代碼,你能告訴我在這段代碼中將使用Observable模式嗎? – JPM 2012-02-14 15:19:58
你是否也看到過有關觀察者和一些方法不是線程安全的? http://stackoverflow.com/q/5123121/346309 – JPM 2012-02-14 17:55:11
我添加了一個例子。沒有意識到線程問題,但是如果您決定使用這種方法,您可以在您提供的鏈接中嘗試解決方案。 – gelupa 2012-02-15 06:57:17