【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("复用单例实例");
});
相关推荐
泯泷1 天前
手搓JSVMM第 8 篇:函数调用:参数、返回值与调用帧
前端·javascript·前端框架
Mr数据杨1 天前
【Codex】用学生入学评估模块建立新生能力画像
android·java·javascript·django·codex·项目开发
苏灿烤鱼1 天前
没有机密文件,也没有付费数据,在浏览器里造一颗"间谍卫星"
前端·javascript·github
泯泷1 天前
手搓JSVM第 5 篇:写第一个编译器:从 AST 生成 IR
前端·javascript·算法
泯泷1 天前
手搓JSVM第 7 篇:控制流:if、while 与 jump
前端·javascript·算法
泯泷1 天前
手搓JSVM第 6 篇:把 IR 编成字节码:emit 与 label fixup
前端·javascript·算法
泯泷1 天前
手搓JSVM第 3 篇:从栈式 VM 到寄存器式 VM:为什么我们选择寄存器
前端·javascript·算法
泯泷1 天前
第 4 篇:让 VM 支持变量:Slot、Environment 与 TDZ
前端·javascript·算法
Coodor1 天前
如何在web浏览器使用js操作CPU卡
开发语言·前端·javascript·cpu卡