【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("复用单例实例");
});
相关推荐
ZC跨境爬虫5 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
kyriewen8 小时前
半夜三点线上崩了,AI替我背了锅——用AI排错,五分钟定位三年老bug
前端·javascript·ai编程
AI_paid_community10 小时前
98.5k Star!GitHub官方开源的这个工具,正在把"vibe coding"扫进历史的垃圾桶
javascript·claude
AI_paid_community10 小时前
用 Claude Code 写了一年代码,装了这 18 个 Skills 之后,我才知道自己一直在"氛围编程"
javascript·面试
隔壁老王111111 小时前
浅谈JavaScript内存管理
javascript
吹牛不交税11 小时前
tree-transfer-vue3 前端插件安装问题解决(--legacy-peer-deps)(其他插件可考虑)适用
前端·javascript·vue.js
Appoint_x11 小时前
设计稿自己会说话:我用 Claude 给 Figma 做了个 AI 上下文插件
前端·javascript
豹哥学前端11 小时前
浏览器console里的双中括号 `[[ ]]`
前端·javascript·ecmascript 6
西洼工作室11 小时前
个人开发者接入阿里云号码认证服务AliCloud-NirvanaPns实现一键登录
python·阿里云·uni-app·全栈·认证授权