标题
由于js是性能孱弱的单线程语言,只要在渲染中执行了一些其他操作,会中断渲染,导致页面卡死,卡顿,吐司不消失等问题。在安卓端可以调用java线程池,把耗时操作写入线程池里面,优化性能。
实现
使用native.js,直接贴出代码
class JavaExecutorPool {constructor() {// #ifdef APP-PLUSconst ScheduledThreadPoolExecutor = plus.android.importClass("java.util.concurrent.ScheduledThreadPoolExecutor")this.executor = new ScheduledThreadPoolExecutor(8)this.reusableRunnable = this.createReusableRunnable();this.block = null;// #endif}createReusableRunnable() {// #ifdef APP-PLUSlet 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-PLUSconsole.log("JavaExecutorPool 执行逻辑")this.block = block; // 动态注入逻辑this.executor.execute(this.reusableRunnable);// #endif}schedule(block, delay) {// #ifdef APP-PLUSif (delay <= 0){this.execute(block)return}setTimeout(() => {this.execute(block)}, delay)// #endif}shutdown() {// #ifdef APP-PLUSthis.executor.shutdown()// #endif}
}
export default JavaExecutorPool;
const javaExecutorPool = new JavaExecutorPool()
使用示例
// 在其他文件中
import javaExecutorPool from './JavaExecutorPool';javaExecutorPool.execute(() => {console.log("复用单例实例");
});