当前位置: 首页> 科技> 数码 > 郑州一建集团有限公司官网_高端品牌护肤品排行榜_域名搜索引擎入口_让顾客心动的句子

郑州一建集团有限公司官网_高端品牌护肤品排行榜_域名搜索引擎入口_让顾客心动的句子

时间:2025/8/2 20:12:45来源:https://blog.csdn.net/LosingCarryJie/article/details/143315720 浏览次数:0次
郑州一建集团有限公司官网_高端品牌护肤品排行榜_域名搜索引擎入口_让顾客心动的句子

适用场景 debug 本地测试

文章目录

  • 代码类 MainThreadMonitor.java
  • 使用方式 Application的attachBaseContext
  • log输出示例

代码类 MainThreadMonitor.java

public class MainThreadMonitor {private static final String TAG = "MainThreadMonitor";private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);public static void startMonitorMainThread(long threshold) {executorService.scheduleAtFixedRate(() -> {checkMainThreadState(threshold);}, 0, threshold, TimeUnit.MILLISECONDS);}private static void checkMainThreadState(long threshold) {AtomicBoolean exec = new AtomicBoolean(false);long startTime = System.currentTimeMillis();Handler mainHandler = new Handler(Looper.getMainLooper());// 预期主线程执行runnable的时候会把 exec置为truemainHandler.post(() -> exec.set(true));executorService.schedule(() -> {// 阈值之后发现 exec 还没有置为true,说明主线程阻塞了if (!exec.get()) {printMainThreadStackTrace(startTime);}}, threshold, TimeUnit.MILLISECONDS);}private static void printMainThreadStackTrace(long startTime) {StackTraceElement[] stackTrace = Looper.getMainLooper().getThread().getStackTrace();long consumeTime = System.currentTimeMillis() - startTime;Log.e(TAG, String.format("start block:(%s) ms  ====================== ", consumeTime));for (StackTraceElement s : stackTrace) {Log.d(TAG, "block: " + s);}}}

使用方式 Application的attachBaseContext

class App : Application() {override fun attachBaseContext(base: Context?) {super.attachBaseContext(base)MainThreadMonitor.startMonitorMainThread(500)}}

log输出示例

在这里插入图片描述
这里需要解释一下 start block 这行的含义,我们看到后面有一个 501ms的耗时,这里并不意味着该方法/函数执行的时间是501ms,而是表述这500ms之内都在此方法中执行,很有可能下一个500ms还是这个堆栈信息,因此 方法实际执行时间 >= 500ms

关键字:郑州一建集团有限公司官网_高端品牌护肤品排行榜_域名搜索引擎入口_让顾客心动的句子

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: