【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("复用单例实例");
});
相关推荐
minglie4 小时前
一个置换问题
javascript
默_笙4 小时前
🌀 别再手动写 Prompt 了!我让 AI 自己循环改到满意为止
javascript
To_OC15 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
To_OC21 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
spmcor1 天前
身份证读卡“无感登录”方案实践:从手动点击到自动检测
uni-app
labixiong1 天前
实现一个能跑的迷你版Promise(一)
前端·javascript·面试
PedroQue991 天前
uni-router v1.8.0新增冷启动守卫补执行
前端·uni-app
weedsfly1 天前
还在用 Axios?你可能需要重新理解 XHR 与 Fetch
前端·javascript·面试
CoderWeen1 天前
从零实现一个 Vue3 流程图编辑器:节点拖拽、贝塞尔连线与框选
前端·javascript
To_OC2 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode