石家莊商城網(wǎng)站搭建多少錢西安百度推廣運(yùn)營
標(biāo)題
由于js是性能孱弱的單線程語言,只要在渲染中執(zhí)行了一些其他操作,會中斷渲染,導(dǎo)致頁面卡死,卡頓,吐司不消失等問題。在安卓端可以調(diào)用java線程池,把耗時操作寫入線程池里面,優(yōu)化性能。
實(shí)現(xiàn)
使用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", {// 用于存儲動態(tài)邏輯run: function () {if (that.block) {console.log("JavaExecutorPool 執(zhí)行動態(tài)邏輯")that.block(); // 執(zhí)行動態(tài)邏輯that.block = null; // 執(zhí)行完后清除邏輯}}});// #endif}execute(block) {// #ifdef APP-PLUSconsole.log("JavaExecutorPool 執(zhí)行邏輯")this.block = block; // 動態(tài)注入邏輯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("復(fù)用單例實(shí)例");
});