【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("复用单例实例");
});
相关推荐
Dxy12393102169 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷9 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
椒哥11 小时前
一天被问几十次"允许",我统计了 517 次,然后写了个插件
前端·javascript·github
kyriewen12 小时前
我测了 6 种防请求竞态的写法:只有 1 种真能打
前端·javascript·程序员
OpsEye12 小时前
企业大模型压测,需要重点关注哪些指标?
javascript·ai编程
像我这样帅的人丶你还13 小时前
我html生成的doc文档为何在手机文档显示不了图片?
前端·javascript
栉甜17 小时前
Vue2学习内容(上)
前端·javascript·vue.js·学习
shmily麻瓜小菜鸡18 小时前
TypeScript 知识点补充(第三部分:工程化与高级类型)
前端·javascript·typescript
Hilaku19 小时前
前端的技术判断力是怎么练出来的?
前端·javascript·程序员
miofly20 小时前
GitHub 今日推荐|floorplan:AI 读代码自动画交互式架构地图
javascript·开源·github