【uniapp】uniapp使用java线程池

标题

由于js是性能孱弱的单线程语言,只要在渲染中执行了一些其他操作,会中断渲染,导致页面卡死,卡顿,吐司不消失等问题。在安卓端可以调用java线程池,把耗时操作写入线程池里面,优化性能。

实现

使用native.js,直接贴出代码

js 复制代码
 class JavaExecutorPool {
    constructor() {
        // #ifdef APP-PLUS
        const ScheduledThreadPoolExecutor = plus.android.importClass("java.util.concurrent.ScheduledThreadPoolExecutor")
        this.executor = new ScheduledThreadPoolExecutor(8)
        this.reusableRunnable = this.createReusableRunnable();
        this.block = null;
        // #endif
    }
     createReusableRunnable() {
         // #ifdef APP-PLUS
         let that = this;
         return plus.android.implements("java.lang.Runnable", {
             // 用于存储动态逻辑
             run: function () {
                 if (that.block) {
                     console.log("JavaExecutorPool 执行动态逻辑")
                     that.block(); // 执行动态逻辑
                     that.block = null; // 执行完后清除逻辑
                 }
             }
         });
         // #endif
     }

     execute(block) {
         // #ifdef APP-PLUS
         console.log("JavaExecutorPool 执行逻辑")
         this.block = block; // 动态注入逻辑
         this.executor.execute(this.reusableRunnable);
         // #endif
     }

    schedule(block, delay) {
        // #ifdef APP-PLUS
        if (delay <= 0){
            this.execute(block)
            return
        }
        setTimeout(() => {
            this.execute(block)
        }, delay)
        // #endif
    }

    shutdown() {
        // #ifdef APP-PLUS
        this.executor.shutdown()
        // #endif
    }
}
export default JavaExecutorPool;
const javaExecutorPool = new JavaExecutorPool()

使用示例

javascript 复制代码
// 在其他文件中
import javaExecutorPool from './JavaExecutorPool';

javaExecutorPool.execute(() => {
    console.log("复用单例实例");
});
相关推荐
申朝先生4 小时前
在vue3中对于普通数据类型是怎么实现响应式的
javascript·vue.js·ecmascript
歪歪1005 小时前
ts-jest与其他TypeScript测试工具的对比
前端·javascript·测试工具·typescript·前端框架
2501_915106325 小时前
苹果软件加固与 iOS App 混淆完整指南,IPA 文件加密、无源码混淆与代码保护实战
android·ios·小程序·https·uni-app·iphone·webview
江城开朗的豌豆5 小时前
小程序登录不迷路:一篇文章搞定用户身份验证
前端·javascript·微信小程序
aesthetician5 小时前
React 19.2.0: 新特性与优化深度解析
前端·javascript·react.js
2501_915921435 小时前
iOS 26 崩溃日志解析,新版系统下崩溃获取与诊断策略
android·ios·小程序·uni-app·cocoa·iphone·策略模式
Django强哥5 小时前
JSON Schema Draft-07 详细解析
javascript·算法·代码规范
U.2 SSD5 小时前
ECharts漏斗图示例
前端·javascript·echarts
江城开朗的豌豆5 小时前
我的小程序登录优化记:从短信验证到“一键获取”手机号
前端·javascript·微信小程序
excel6 小时前
Vue Mixin 全解析:概念、使用与源码
前端·javascript·vue.js