Handler、Looper、MessageQueue的理解:应用(三)

一、实现线程之间通信

方式一

/**
 * 线程1往线程2传递数据
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }
    public void btn(View v) throws InterruptedException {
        MyThread2 myThread2=new MyThread2();
        myThread2.start();
        Thread.sleep(1000);
        MyThread1 myThread1=new MyThread1();
        myThread1.start();
    }


    class MyThread1 extends Thread{
        @SuppressLint("HandlerLeak")
        @Override
        public void run() {
            super.run();
            handler2.sendEmptyMessage(3);
        }
    }

    Handler handler2;
    class MyThread2 extends Thread{

        @SuppressLint("HandlerLeak")
        @Override
        public void run() {
            super.run();
            Looper.prepare();
            handler2=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    System.out.println(Thread.currentThread()+"   "+msg.what);
                }
            };
            Looper.loop();
        }
    }

}
方式二:
/**
 * 使用HandlerThread 的looper方式实现线程1往线程2传递数据
 */
public class HandlerDemoActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_handler_demo);
		handlerThread = new HandlerThread("my-thread");
		handlerThread.start();

	}

	MyThread2 myThread2 = null;

	public void btn(View v) throws InterruptedException {
		myThread2 = new MyThread2();
		myThread2.start();
		Thread.sleep(1000);

		MyThread1 myThread1 = new MyThread1();
		myThread1.start();

	}

	class MyThread1 extends Thread {
		@Override
		public void run() {
			super.run();
			handler2.sendEmptyMessage(3);
		}
	}

	HandlerThread handlerThread;

	Handler handler2;

	class MyThread2 extends Thread {

		@Override
		public void run() {
			super.run();
			handler2 = new Handler(handlerThread.getLooper()) {
				public void handleMessage(Message msg) {
					System.out.println(Thread.currentThread() + "   "
							+ msg.what);
				};
			};

		}
	}

}

android中更新UI的几种方式

1、handler.sendMessage()

2、handler.post(Runnable r)

3、runOnUIThread();

4、View.post(Runnable r)

从源码分析实现原理就是用的handler的方式。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值