当前位置: 首页 > news >正文

Android Handler的runWithScissors手段

Handler的runWithScissors方法是隐藏API,用于执行同步任务(即让另一个线程执行一个任务,当前线程先阻塞,等待该执行完,之后当前线程再继续执行)。源码如下:

BlockingRunnable代码如下:

ok 源码就这些。 当前线程 wait(阻塞),等待handler所关联的线程执行完任务后唤醒当前线程。可以用于执行同步任务。timeOut为超时时间。

隐藏API不方便直接调用。把这段代码复制出来测试下, 测试代码如下:

package com.example.myapplication;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
public class Test {MyHandler handler;public void testRunWithScissors() {Thread thread1 = new Thread(){@Overridepublic void run() {Log.d("zx", "thread1 start , threadID:" + Thread.currentThread().getId());Looper.prepare();handler = new MyHandler(Looper.myLooper());Looper.loop();}};thread1.start();Thread thread2 = new Thread() {@Overridepublic void run() {Log.d("zx", "thread2 start , threadID:" + Thread.currentThread().getId());// 线程2等待线程1执行一个任务, 执行完该任务后,线程2再做其他事。boolean res = handler.runWithScissors2(new Runnable() {@Overridepublic void run() {// 线程1中会执行这个任务Log.d("zx", "current Thread, threadID:" + Thread.currentThread().getId()+ ", task start ...");for (int i = 0; i < 5; i++) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}Log.i("zx", "i = " + i);}Log.i("zx", "task finish");}}, 1000);Log.d("zx", "task finish, result: " + res + ", thread2 continue ...");}};try {Thread.sleep(10); // 防止线程1还没跑起来handler为空} catch (InterruptedException e) {e.printStackTrace();}thread2.start();}public static class MyHandler extends Handler {public MyHandler(Looper looper) {super(looper);}// 同步执行任务。 意思是,阻塞当前线程,等待另一个线程执行完该任务后,当前线程再继续执行. timeout为超时时间。 返回值表示任务执行是否成功public final boolean runWithScissors2(Runnable r, long timeout) { // 不能和隐藏api的方法同名,所以换了方法名。if (r == null) {throw new IllegalArgumentException("runnable must not be null");}if (timeout < 0) {throw new IllegalArgumentException("timeout must be non-negative");}if (Looper.myLooper() == getLooper()) { // 特殊情况,没有切换线程,就在当前线程执行。r.run();return true;}BlockingRunnable br = new BlockingRunnable(r);return br.postAndWait(this, timeout);}private static final class BlockingRunnable implements Runnable {private final Runnable mTask;private boolean mDone;public BlockingRunnable(Runnable task) {mTask = task;}@Overridepublic void run() {try {mTask.run();} finally {synchronized (this) {mDone = true;notifyAll();}}}public boolean postAndWait(Handler handler, long timeout) {if (!handler.post(this)) {return false;}synchronized (this) {if (timeout > 0) {final long expirationTime = SystemClock.uptimeMillis() + timeout;while (!mDone) {long delay = expirationTime - SystemClock.uptimeMillis();if (delay <= 0) {return false; // timeout 超时了}try {wait(delay);} catch (InterruptedException ex) {}}} else {while (!mDone) {try {wait();} catch (InterruptedException ex) {}}}}return true;}}}
}

然后在activity里直接测试:

打印:

ok. 结果符合预期。

http://www.rkmt.cn/news/28658.html

相关文章:

  • 完整教程:ImmuCellAI 免疫浸润分析
  • Deepoc具身智能模型:为传统机器人注入“灵魂”,重塑建筑施工现场安全新范式 - 指南
  • P5285 [十二省联考 2019] 骗分过样例
  • Error: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试及其解决方法
  • 2025.10.23考试记录
  • 2025小型低温/工业/风冷/一体式螺杆冷冻机厂家推荐:东莞凯诺机械专业制冷解决方案
  • noipd8t2 - Slayer
  • OJ模拟面试3(异步判题架构)
  • 破局内容运营效率:2025 微信编辑器 10 款深度测评
  • 2025氮化硼陶瓷高温绝缘体/坩埚/套管/基板/高温构件/耐腐蚀构件推荐榜:福维科(山东)引领国产化,3 家企业凭技术实力登榜
  • 利用排列组合法实现TOPN路径计算
  • 达梦数据库获取判断字段中的json数据中的值
  • 2025包装机/全自动包装机/非标定制生产线厂家推荐昆仑智能装备,专业高效!
  • FastDFS 安装部署 数据迁移 centos 安装 FastDFS
  • 2025摩托车厂家推荐:浙江天鹰机车,专业制造与创新设计之选
  • Linux基础——wipefs磁盘数据擦除工具
  • python 异步调用语法
  • KAPE 0.8.3.0发布:数字取证工具新版本详解
  • 哇哦杯题解民间版
  • 2025移动泵车/防汛泵车/水泵机组厂家推荐潍坊山藤动力,专业高效排水解决方案
  • 第一!天翼云引领中国教育公有云市场
  • 第一次大作业心得
  • 基于粒子群优化(PSO)算法的PID控制器参数整定
  • 2025棒球帽/卫衣/羽绒服品牌推荐,COVERNAT潮流服饰厂家精选
  • 如何在CentOS 7上安装bzip2-1.0.6-13.el7.x86_64.rpm RPM包(详细步骤) - 详解
  • 2025 年度撕碎机厂家最新推荐权威榜单:涵盖金属 / 塑料 / 木材 / 固废等多物料处理,精选实力企业破解选型难题
  • C程序设计语言_1.1_开篇入门
  • 2025年10月广州办公室设备搬运公司全景解析报告,基于专业测评的技术、性能及市场优势深度分析
  • 2025年专业的上海Micro-LED显示屏推荐TOP生产厂家
  • 2025年质量好的工业不锈钢链轮最新TOP厂家推荐