【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 分钟前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
万物得其道者成4 分钟前
UniApp 多端滑块验证码插件 zxj-slide-verify 实用指南
uni-app
蓝帆傲亦2 小时前
支付宝小程序性能暴增秘籍:UniApp项目极限优化全攻略
小程序·uni-app
铅笔侠_小龙虾2 小时前
Flutter 实战: 计算器
开发语言·javascript·flutter
大模型玩家七七2 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
2501_944711433 小时前
JS 对象遍历全解析
开发语言·前端·javascript
发现一只大呆瓜3 小时前
虚拟列表:支持“向上加载”的历史消息(Vue 3 & React 双版本)
前端·javascript·面试
阔皮大师4 小时前
INote轻量文本编辑器
java·javascript·python·c#
lbb 小魔仙4 小时前
【HarmonyOS实战】React Native 表单实战:自定义 useReactHookForm 高性能验证
javascript·react native·react.js
_codemonster4 小时前
Vue的三种使用方式对比
前端·javascript·vue.js