I would like to create two threads (T1 and T2) from main thread that can communicate with each other. I am looking at the best way to accomplish this. My idea is to do this with the handler. Is this OK? The problem is that I do not know how can T1 obtain a handler reference for T2 and vice versa.
EDIT.
Let me explain situation in more detail. If some condition happens in T1 I want signal that to T2 so that T2 can do some other work.
You can do something like this:
public class Test {
static abstract class MyThread extends Thread implements Callback{
Callback mCallback;
public void setCallBack(Callback pCallBack){
mCallback = pCallBack;
}
}
static interface Callback{
public void onAction(Object... args);
}
public static void main(String args[]){
MyThread T1 = new MyThread(){
@Override
public void onAction(Object... args) {
//code when onAction is called.
}
public void run(){
//T1 thread code here
//if some condition
//call the Callback
mCallback.onAction();
}
};
MyThread T2 = new MyThread(){
@Override
public void onAction(Object... args) {
//code when onAction is called.
//"Other work"
}
public void run(){
//T2 thread code here
}
};
T1.setCallBack(T2);
T2.setCallBack(T1);
T1.start();
T2.start();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.