Android Handler的runWithScissors手段

news/2025/10/23 19:35:47/文章来源:https://www.cnblogs.com/wzzkaifa/p/19161470

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.mzph.cn/news/944627.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Idea提高制作效率的快捷键最佳学习方式

Idea提高制作效率的快捷键最佳学习方式pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Mon…

Elasticsearch8容器化部署 - 实践

Elasticsearch8容器化部署 - 实践2025-10-23 19:30 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !impor…

ski 和 db 模块的通信

ski 和 db 模块的通信 qt 信号槽 创建一个单例类,在 db 模块发送信号,在ski 模块接收 class abSignalEmitter : public QObject {Q_OBJECTpublic:static abSignalEmitter& instance() {static abSignalEmitter i…

rocky10自己手动换源

rocky10手动换源 动作背景:自己做小实验需要inistall ,但是安装之后配置的源文件有问题,报错 流程: 1.先确认系统版本 cat /etc/rocky-release 2.备份原有配置(必要动作) mkdir -p /etc/yum.repos.d/backup mv /…

完整教程:ImmuCellAI 免疫浸润分析

完整教程:ImmuCellAI 免疫浸润分析pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco…

4.6.2版本来了!快来看看新版本有哪些改动

产品更新概览 功能修复: 修复云托管自定义日期无法设置问题; 修复资产库中放置模式使用问题; 修复鲸孪生中gltf格式模型无法添加到资产库问题; 修复鲸孪生中已知情况下fbx模型导入失败问题; 修复菜单组件首次触发…

2025-10-22 ZR-J 模拟赛 赛后总结【ZR】

光速打完前三题,然后被 T4 击败。 结果挂完了。 50+10+100+0。 T1 Letters 题意 给定 \(n\) 个单词,对于这些单词组成的集合的所有子集,问这些子集中 a 到 z 26 个字母均出现过至少一次的子集总数。 赛时 经过 0 秒…

Deepoc具身智能模型:为传统机器人注入“灵魂”,重塑建筑施工现场安全新范式 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

[grep] grep stream 2, the error message

In Unix-like systems, stdout (standard output) is stream 1, and stderr (standard error) is stream 2. By default, grep reads from stdin, which typically receives stdout — not stderr. To have grep searc…

P5285 [十二省联考 2019] 骗分过样例

绝世好题P5285 [十二省联考 2019] 骗分过样例 题目链接 前言 一道很考验数论水平、耐心与注意力的题 \(16\) 个测试点中有 \(14\) 个是我独立完成的,剩余的测试点 #7,#13 分别参考了题解和讨论区题目大意 下发 \(16\…

Liferay Portal与DXP集合提供程序存在授权缺失漏洞分析

本文详细分析了CVE-2025-62247漏洞,该漏洞影响Liferay Portal和DXP的集合提供程序组件,存在授权缺失问题,允许实例用户跨实例读取和选择未经授权的蓝图配置。Liferay Portal和DXP集合提供程序存在授权缺失漏洞 漏洞…

MapGIS Objects Java计算一条三维线段与一个三角形所在的平面的交点 - 教程

MapGIS Objects Java计算一条三维线段与一个三角形所在的平面的交点 - 教程pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-famil…

layui时间与日期选择器,时间范围查询数据,后端springboot

需求 我需要根据时间段,比如10.1号——10月31号,查询此时间段的对应数据。 实体类 user:含有姓名,性别。其中有个入职时间private Date interviewTime; 我们需要根据入职时间,查询指定范围的数据 前端<div cla…

读书笔记:OpenPBR 规范(2)

3. 模型 ​ ​​​  使用前述的公式和参数化方法,我们现在来具体说明 OpenPBR 表面模型的结构。我们首先描述“非薄壁”情况(“薄壁”情况下的结构有所不同),其材质结构非正式地如下图所示:​ ​​​  总而言…

轻量级图片信息解析程序

简介 平时的工作中我经常需要获取图片文件的一些基本信息(宽度、高度、通道数、色深)。因为项目依赖 opencv,以前都是直接用的 opencv 来读入图片后获取这些信息的,opencv 读入图片是读取所有的数据,会影响效率和…

2025.10.23 闲话-全局位运算 max 的解法

我不会。2025.10.23 闲话-全局位运算 \(max\) 的解法 三部分将使用不同的策略求解。 Part.1 \(xor-max\) 这一类问题算是最简单的,每次插入一个数,在 \(Trie\) 树上跳,先查询这个数产生的最大值。 查询时如果当前位…

express 模块学习 - 东方不败-

01.js// npm i express@4.17.1 // npm i -g nodemon // nodemon xx.js const express = require(express) const app = express() app.listen(3000,()=>{console.log("hello zhangdan") })app.get(/user…

习题-无限集与选择公理

习题1. 不用选择公理定义一个单射\(f:\mathbb{Z}_+\rightarrow X^{\omega}\),其中\(X\)为二元素集\(\{0,1\}\)。2. 如果有可能的话,试对下列各个集族不用选择公理而求出来一个选择函数。(a) \(\mathbb{Z}_+\)的所有非…

Error: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试及其解决方法

这一报错意味着当前试图使用的端口被占用。 一般情况下使用 netstat -ano|findstr <port> 就可以查出来,然后taskkill /pid <id>/F就好 但这次没有查出有使用,但确实有报错。经查是docker容器里预先跑的…

题解:CF2115F1 Gellyfish and Lycoris Radiata (Easy Version)

节选自:Codeforces Round 1028 (Div. 1) 这题非常好玩,也非常达芬,我做了 \(1\) 天半才过。 我们考虑到问题是在线,因此可以想到支持在线的操作分块(虽然我没想到),每 \(\sqrt q\) 个操作分成一个操作块。考虑到…