工作线程到工作线程的通信 [英] Worker Thread to Worker Thread Communication
本文介绍了工作线程到工作线程的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java/Android-
Java/Android -
我找不到任何从工作线程到工作线程的通信示例.这些示例始终涉及UiThread.
I am unable to find any Worker Thread to Worker Thread communication examples. The examples always involve the UiThread.
我有一个HandlerThread获取工作,而HandlerThread将工作分散到多个工作线程中.我希望多个工作线程可以通讯回HandlerThread.
I have a HandlerThread that gets fed work and the HandlerThread spreads the work onto multiple worker threads. I want the multiple worker threads to communicate back to the HandlerThread.
我所能做的就是让工作线程通过Handler与UiThread通信.谢谢!
All I have been able to do is have the worker threads communicate with the UiThread via Handler. Thanks!
推荐答案
public class ModelFragment extends Fragment implements Handler.Callback {
Handler backHandler1, backHandler2, mainHandler;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
HandlerThread backThread1 = new HandlerThread("BACK_THREAD_1");
backThread1.start();
backHandler1 = new Handler(backThread1.getLooper(), this);
HandlerThread backThread2 = new HandlerThread("BACK_THREAD_2");
backThread2.start();
backHandler2 = new Handler(backThread2.getLooper(), this);
mainHandler = new Handler(Looper.getMainLooper(), this);
// sending message from main thread to thread 1
backHandler1.obtainMessage(BACK1_WHAT, backObj).sendToTarget();
}
@Override
public boolean handleMessage(Message msg) {
switch(msg.what){
case BACK1_WHAT:
// this code runs on thread 1
// sending message to thread 2 from thread 1
backHandler2.obtainMessage(BACK2_WHAT, backObj1).sendToTarget();
return true;
case BACK2_WHAT:
// this code runs on thread 2
// sending message to thread 1 from thread 2
backHandler1.obtainMessage(BACK1_WHAT, backObj2).sendToTarget();
// sending message to main thread from thread 2
mainHandler.obtainMessage(MAIN_WHAT, backObj2).sendToTarget();
return true;
case MAIN_WHAT:
// runs on ui thread
return true;
}
return false;
}
@Override
public void onDestroy() {
if(null != backHandler1) {
backHandler1.removeCallbacksAndMessages(null);
if(null != backHandler1.getLooper())
backHandler1.getLooper().quit();
}
if(null != backHandler2) {
backHandler2.removeCallbacksAndMessages(null);
if(null != backHandler2.getLooper())
backHandler2.getLooper().quit();
}
super.onDestroy();
}
}
这篇关于工作线程到工作线程的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文