多个线程之间的通信
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; /** * 1、子线程A发消息给子线程B * 2、子线程B发消息给主线程 * 3、主线程更新界面 * 具体实现思路 * 1、构建两个工作线程,SubThreadA和SubThreadB * 2、工作线程启动时,在两个工作线程中构建两个Looper对象 * 3、构建两个工作线程Handler对象 SubHandlerA和SubHandlerB * 4、在SubHandlerA中获取消息并将消息传给SubHandlerB对象 * 5、在SubHandlerB中获取SubHandlerA的消息,并将消息传给主线程 * 6、主线程的MainHandler对象获取消息以后更新界面 * */ public class MainActivity extends Activity { private Looper looperA; private Looper looperB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new SubThreadA().start(); new SubThreadB().start(); } public void doClick(View view){ switch (view.getId()) { case R.id.button1:sendMessage();break; case R.id.button2: looperA.quit(); looperB.quit(); finish();break; } } public void sendMessage(){ Handler h=new SubHandlerA(); Message.obtain(h, 1, "HelloWorld!").sendToTarget(); } /**线程A*/ class SubThreadA extends Thread{ @Override public void run() { Looper.prepare();//Looper对象构建同时MQ也会构建 looperA=Looper.myLooper(); Looper.loop(); } } /**线程B*/ class SubThreadB extends Thread{ @Override public void run() { Looper.prepare(); looperB=Looper.myLooper(); Looper.loop(); } } /**ThreadA的Handler*/ class SubHandlerA extends Handler{ public SubHandlerA(){ super(looperA); } @Override public void handleMessage(Message msg) { //1.获取线程A的消息 //Object obj=msg.obj; //2.构建线程B的HandlerB的对象 Handler handler=new SubHandlerB(); //3.将消息传给HandlerB对象所对应的线程 Message.obtain(handler, 2, msg.obj).sendToTarget(); } } /**ThreadB的Handler*/ class SubHandlerB extends Handler{ public SubHandlerB(){ super(looperB); } /** * 此方法用于处理消息:处理线程A发过来的消息 * |-->获取ThreadA的消息 * |-->将消息发给主线程 * * */ @Override public void handleMessage(Message msg) { //获取线程A的消息 //Object mess=msg.obj; //构建主线程的handler Handler handler=new MainHandler(); //借助主线程的Handler将消息发送到主线程??? Message.obtain(handler, 3, msg.obj).sendToTarget(); } } /**主线程的Handler*/ class MainHandler extends Handler{ public MainHandler() { super(Looper.getMainLooper()); } @Override public void handleMessage(Message msg) { setTitle((String)msg.obj); } } }
文章名称:多个线程之间的通信
转载来源:http://azwzsj.com/article/gpiisi.html