子线程与主线程通信的其他方法概述

前面有2篇博客单独讲解了子线程和主线程之间的通信:Thread-Handler-Message和AsyncTask。实现异步通信还有以下的3种方法:

第一种:runOnUiThread(Runnable action)
此方法是在Activity中定义的,官方文档做的说明是:
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.即:这个方法是要运行在主线程的. 如果当前线程不是主线程,就通过post方法传递给主线程队列执行,如果已经在主线程,就立刻执行。

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

代码示例:比如开辟子线程sleep2s, 之后进入某一个界面:这里可以不用Thread-Handler-Message来处理,直接用runOnUiThread。

new Thread() {
                public void run() {
                    SystemClock.sleep(2000);
                    // 在主线程进入某一界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            enterActivity();
                        }
                    });
                };
            }.start();

第二种:View方法中的post(Runnable action):返回值为true的话,说明action 被成功的添加到消息队列中了(message queue),返回值为false的话处理消息队列的looper退出了。

第三种:View 方法中的postDelayed(Runnable action, long delayMillis)。返回值是boolean.它也是将action 添加到消息队列中,但是是在延迟一定时间之后开始执行。需要注意的是当返回值为true的时候,action不一定会被处理,因为looper有可能已经退出,那么发送的这条消息就会被丢弃。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Python 中,线程线程之间可以通过共享变量或队列进行通信。 一种常见的方法是使用共享变量。在线程中创建一个共享变量,然后将其作为参数传递给线程线程可以修改共享变量的值,线程可以读取该值。需要注意的是,对于多个线程同时访问共享变量时,需要采取适当的同步机制(如锁)来避免竞争条件。 另一种方法是使用队列(Queue)。线程可以创建一个队列,并将其作为参数传递给线程线程可以将数据放入队列中,而线程可以从队列中读取数据。队列提供了线程安全的操作,因此不需要显式的同步机制。 下面是一个简单示例,演示了线程线程之间的通信: ```python import threading import queue def child_thread(queue): # 线程向队列中放入数据 data = 'Hello from child thread!' queue.put(data) def main_thread(queue): # 线程从队列中读取数据 data = queue.get() print(data) def main(): # 创建一个队列 q = queue.Queue() # 创建线程并传递队列 t = threading.Thread(target=child_thread, args=(q,)) t.start() # 线程从队列中读取数据 main_thread(q) if __name__ == '__main__': main() ``` 在上面的示例中,线程创建了一个队列 `q`,然后创建一个线程并将队列作为参数传递给线程线程向队列中放入数据。线程调用 `main_thread` 函数从队列中读取数据,并打印出来。 这只是其中一种通信方式,具体的实现方式可以根据实际需求来选择。同时,还有其他更高级的通信机制,如事件、信号量等,可以根据具体情况选择使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值