线程通信
Handler
获取到哪个线程的Handler,就可以给这个线程发送消息。
Looper
线程间通信的桥梁。
案例
更新UI数据
动态更新Activity界面上面的数据。3s后,让界面上的数字每秒后增加1。
- UI线程创建Handler,负责接收普通线程发送的数字增加消息并更新Activity界面。
Handler uiHandler = null;
public void initHandler(){
uiHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
Log.d(TAG, String.format("[uiHandler][handleMessage]Message=%s", msg));
switch (msg.what){
case Config.ADD_ONE:
number++;
textView.setText(String.valueOf(number));
break;
default:
Log.d(TAG, String.format("[uiHandler][handleMessage]Other what of message %s", msg.what));
break;
}
super.handleMessage(msg);
}
};
}
- 创建普通线程,使用UI线程的Handler向UI线程发送数字增加消息。
public void startAddNumberThread(){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
while (true) {
Message message = uiHandler.obtainMessage();
message.what = Config.ADD_ONE;
uiHandler.sendMessage(message);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
- 实现效果。
- 示例源码: handler进程通信-UpdateUIThread,有用的话敬请Star。
两个普通线程间的通信
- 创建两个普通线程:threadA、threadB。
- threadA创建后,等待1s(等threadB也完成创建),向threadB发送首条消息。
- threadB收到threadA的消息后,回复1条消息。
- threadA收到threadB回复的消息后,通信结束。
创建threadA,等待threadB创建完成后给threadB发送一条消息。
new Thread(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
handlerA = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.d(TAG, String.format("[ThreadA][UseHandlerA][GetMessage]\t%s", msg.obj));
}
};
// wait for handlerB isn't null
Thread.sleep(1000);
while (handlerB==null) {
;
}
Message msg = Message.obtain();
msg.what = Config.THREADA;
msg.obj = "Hi thread B, this's thread A";
Log.d(TAG, String.format("[ThreadA][UseHandlerB][SendMessage]\t%s", msg.obj));
handlerB.sendMessage(msg);
//enter loop.
Looper.loop();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
创建threadB。接收threadA发送的消息后回复一条消息。
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
handlerB = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.d(TAG, String.format("[ThreadB][UseHandlerB][GetMessage]\t%s", msg.obj));
Message msgB = Message.obtain();
msgB.what = Config.THREADA;
switch (msg.what) {
case Config.THREADA:
msgB.obj = "Dear thread A, i'am fine, thanks and bye.";
Log.d(TAG, String.format("[ThreadB][UseHandlerA][SendMessage]\t%s", msgB.obj));
handlerA.sendMessage(msgB);
break;
}
}
};
Looper.loop();
}
}).start();
结果输出
[ThreadA][UseHandlerB][SendMessage] Hi thread B, this's thread A
[ThreadB][UseHandlerB][GetMessage] Hi thread B, this's thread A
[ThreadB][UseHandlerA][SendMessage] Dear thread A, i'am fine, thanks and bye.
[ThreadA][UseHandlerA][GetMessage] Dear thread A, i'am fine, thanks and bye.
源码: handler进程通信-Demo2ThreadAToThreadB,有用的话敬请Star。