我有一个线程,在其中需要定期执行一些检查、从网络获取文件并向主UI线程发送消息。我甚至需要在每个工作线程的循环中使用UI线程参数(如地图可见区域)。因此,我认为我需要在UIThread和WorkerThread之间实现双向通信。
另一个问题是我需要保存添加到地图上的每个标记的标识符。我想将map.addMarker的结果保存在我的自定义数组中,该数组存储在我的worker线程中。这意味着在更新地图的uithread中,我应该告诉workerThread更新标记数组。
以下是我的实际工作线程示例:
我的实际问题是,当UI线程结束处理从工作线程接收的消息时,我应该对工作线程执行一个操作。
我想到了两个解决方案:
1)在工作线程上等待,直到UI线程处理完消息。
2)在UI线程上处理消息,然后向工作线程发送消息。
我不知道如何执行解决方案1,所以我尝试了解决方案2。我尝试将一个looper添加到我的工作线程(RUN子程序)中,方法如下:
问题是在 Looper.loop() 之后没有执行任何代码。我读到这是正常的。我阅读了许多文章,但我不知道如何允许执行 while 循环,并同时处理来自 UI 线程的消息。 希望问题清楚了。请给我建议最佳解决方案。
另一个问题是我需要保存添加到地图上的每个标记的标识符。我想将map.addMarker的结果保存在我的自定义数组中,该数组存储在我的worker线程中。这意味着在更新地图的uithread中,我应该告诉workerThread更新标记数组。
以下是我的实际工作线程示例:
class MyThread extends Thread {
private Handler handler;
private MainActivity main;
public MyThread (MainActivity mainClass, Handler handlerClass) {
this.main=mainClass;
this.handler = handlerClass;
}
@Override
public void run(){
while(true){
sleep(2000);
//do my stuffs
//....
//prepare a message for the UI thread
Message msg = handler.obtainMessage();
msg.obj= //here i put my object or i can even use a bundle
handler.sendMessage(msg); //with this i send a message to my UI thread
}
}
}
我的实际问题是,当UI线程结束处理从工作线程接收的消息时,我应该对工作线程执行一个操作。
我想到了两个解决方案:
1)在工作线程上等待,直到UI线程处理完消息。
2)在UI线程上处理消息,然后向工作线程发送消息。
我不知道如何执行解决方案1,所以我尝试了解决方案2。我尝试将一个looper添加到我的工作线程(RUN子程序)中,方法如下:
class MyThread extends Thread {
private Handler handler;
private MainActivity main;
public MyThread (MainActivity mainClass, Handler handlerClass) {
this.main=mainClass;
this.handler = handlerClass;
}
@Override
public void run(){
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// Act on the message received from my UI thread doing my stuff
}
};
Looper.loop();
while(true){
sleep(2000);
//do my stuffs
//....
//prepare a message for the UI thread
Message msg = handler.obtainMessage();
msg.obj= //here i put my object or i can even use a bundle
handler.sendMessage(msg); //with this i send a message to my UI thread
}
}
}
问题是在 Looper.loop() 之后没有执行任何代码。我读到这是正常的。我阅读了许多文章,但我不知道如何允许执行 while 循环,并同时处理来自 UI 线程的消息。 希望问题清楚了。请给我建议最佳解决方案。
BlockingQueue
视为在线程之间发送消息的机制。 - Gray