gpt4 book ai didi

java - 工作线程到工作线程通信

转载 作者:搜寻专家 更新时间:2023-11-01 09:27:59 27 4
gpt4 key购买 nike

Java/安卓-

我找不到任何工作线程到工作线程的通信示例。这些示例总是涉及 UiThread。

我有一个获取工作的 HandlerThread,HandlerThread 将工作分散到多个工作线程上。我希望多个工作线程与 HandlerThread 通信。

我所能做的就是让工作线程通过处理程序与 UiThread 通信。谢谢!

最佳答案

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

关于java - 工作线程到工作线程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49392743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com