How:Thread、Runnable和Handler的完美结合

本文介绍了消息队列MessageQueue的概念及应用,同时深入探讨了Runnable接口如何用于在不同线程中执行任务。此外,还详细讲解了Handler的作用及其实现方式,通过一个具体的进度条更新示例展示了其工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Thead:

    1.有自己的消息队列:MessageQueue  

Runnable:

    1.public interface

    2.Represents a command that can be executed

    3.often used to run code in a different Thread

    4.理解:它定义了一组操作,这组操作将被以消息的形式发给另一个Thread,是接收到该消息的Thread执行这组操作

    5.常用实现形式:

       

    new Runnable() {
        public void run() {
            //你的一组操作
        }
    }


Handler:

    1.A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue

    2. Each Handler instance is associated with a single thread and that thread's message queue

    3.it is bound to the thread / message queue of the thread that is creating it 

    4.常用方法:

post( Runnable r)
实例:(实现进度条)

new Thread(new Runnable() {
            public void run() {
                while (mProgressStatus < 100) {
                    mProgressStatus++;
                    try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    // Update the progress bar
                    mHandler.post(new Runnable() {
                        public void run() {
                            mProgress.setProgress(mProgressStatus);
                        }
                    });
                }
            }
        }).start();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值