【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("复用单例实例");
});
相关推荐
zhutoutoutousan6 分钟前
解决 Supabase “permission denied for table XXX“ 错误
javascript·数据库·oracle·个人开发
cesske6 分钟前
uniapp打包报错:重新在manifest.json中生成自己的APPID
uni-app·json
小马大咖20 分钟前
在UniApp中开发微信小程序实现图片、音频和视频下载功能
微信小程序·小程序·uni-app
小镇学者1 小时前
【JS】Vue 3中ref与reactive的核心区别及使用场景
前端·javascript·vue.js
xosg1 小时前
HTMLUnknownElement的使用
java·前端·javascript
江畔柳前堤2 小时前
PyQt学习系列05-图形渲染与OpenGL集成
开发语言·javascript·人工智能·python·学习·ecmascript·pyqt
2301_808913833 小时前
如何把vue项目部署在nginx上
javascript·vue.js·ecmascript
Lhuu(重开版3 小时前
Vue:axios(GET请求)
前端·javascript·vue.js
sg_knight4 小时前
Flutter跨平台通信实战|3步打通Android原生能力,实现底层API调用!
android·前端·javascript·flutter·跨平台·web·双向通信
yz-俞祥胜5 小时前
【疑难杂症】Vue前端下载文件无法打开 已解决
前端·javascript·vue.js