鸿蒙系统线程管理

2020-11-07  本文已影响0人  裴云飞

概述

在启动应用时,系统会为该应用创建一个主线程。该线程随着应用创建或消失,界面的显示和更新等操作,都是在主线程上进行。与安卓和iOS一样,鸿蒙系统也不允许在主线程里面做耗时操作,耗时操作需要在子线程中处理。

TaskDispatcher分发任务

如果应用的业务逻辑比较复杂,可能需要创建多个线程来执行多个任务。这种情况下,代码复杂难以维护,任务与线程的交互也会更加繁杂。要解决此问题,开发者可以使用“TaskDispatcher”来分发不同的任务。TaskDispatcher是一个任务分发器,它是 Ability分发任务的基本接口,隐藏任务所在线程的实现细节。

为保证应用有更好的响应性,我们需要设计任务的优先级。在主线程线程上运行的任务默认以高优先级运行,如果某个任务无需等待结果,则可以用低优先级。

优先级 详细描述
HIGH 最高任务优先级,比默认优先级、低优先级的任务有更高的几率得到执行。
DEFAULT 默认任务优先级, 比低优先级的任务有更高的几率得到执行。
LOW 低任务优先级,比高优先级、默认优先级的任务有更低的几率得到执行。

TaskDispatcher具有多种实现,每种实现对应不同的任务分发器。在分发任务时可以指定任务的优先级,由同一个任务分发器分发出的任务具有相同的优先级。系统提供的任务分发器有 GlobalTaskDispatcher、ParallelTaskDispatcher、SerialTaskDispatcher 、SpecTaskDispatcher。

TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
String dispatcherName = "parallelTaskDispatcher";
TaskDispatcher parallelTaskDispatcher = createParallelTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
String dispatcherName = "serialTaskDispatcher";
TaskDispatcher serialTaskDispatcher = createSerialTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
TaskDispatcher uiTaskDispatcher = getUITaskDispatcher();

MainTaskDispatcher:由 Ability 执行 getMainTaskDispatcher() 创建并返回。

TaskDispatcher mainTaskDispatcher= getMainTaskDispatcher()

用例

globalTaskDispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(label, "sync task1 run");
            }
        });
HiLog.info(label, "after sync task1");
 
globalTaskDispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(label, "sync task2 run");
            }
        });
HiLog.info(label, "after sync task2");

// 执行结果如下:
// sync task1 run
// after sync task1
// sync task2 run
// after sync task2
Revocable revocable =  globalTaskDispatcher.asyncDispatch(new Runnable() {
        @Override
            public void run() {
                HiLog.info(label, "async task1 run");
            }
        });
HiLog.info(label, "after async task1");
 
// 执行结果可能如下:
// after async task1
// async task1 run
 final long callTime = System.currentTimeMillis();
 final long delayTime = 50;
 Revocable revocable =  globalTaskDispatcher.delayDispatch(new Runnable() {
            @Override
            public void run() {
                HiLog.info(label, "delayDispatch task1 run");
                final long actualDelayMs = System.currentTimeMillis() - callTime;
                HiLog.info(label, "actualDelayTime >= delayTime : %{public}b" + (actualDelayMs >= delayTime));
            }
        }, delayTime );
 HiLog.info(label, "after delayDispatch task1");
 
// 执行结果可能如下:
// after delayDispatch task1
// delayDispatch task1 run
// actualDelayTime >= delayTime : true
void groupTest(Context context) {
    TaskDispatcher dispatcher = context.createParallelTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
    // 创建任务组。
    Group group = dispatcher.createDispatchGroup();
    // 将任务1加入任务组,返回一个用于取消任务的接口。
    dispatcher.asyncGroupDispatch(group, new Runnable(){
        public void run() {
            HiLog.info(label, "download task1 is running");
            downLoadRes(url1);
        }
    });
   // 将与任务1相关联的任务2加入任务组。
    dispatcher.asyncGroupDispatch(group, new Runnable(){
        public void run() {
            HiLog.info(label, "download task2 is running");
            downLoadRes(url2);
        }
    });
    // 在任务组中的所有任务执行完成后执行指定任务。
    dispatcher.groupDispatchNotify(group, new Runnable(){
        public void run() {
            HiLog.info(label, "the close task is running after all tasks in the group are completed");
            closeApp();
        }
    });
}
​
// 可能的执行结果:
// download task1 is running
// download task2 is running
// the close task is running after all tasks in the group are completed
 
// 另外一种可能的执行结果:
// download task2 is running
// download task1 is running
// the close task is running after all tasks in the group are completed
void postTaskAndRevoke(Context context) {
    TaskDispatcher dispatcher = context.getUITaskDispatcher();
    Revocable revocable = dispatcher.delayDispatch(new Runnable(){
         HiLog.info(label, "delay dispatch");
    }, 10);
    boolean revoked = revocable.revoke();
    HiLog.info(label, "%{public}b", revoked);
}
​
// 一种可能的结果如下 :
// true
TaskDispatcher dispatcher = context.createParallelTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
    // 创建任务组。
    Group group = dispatcher.createDispatchGroup();
    // 将任务加入任务组,返回一个用于取消任务的接口。
    dispatcher.asyncGroupDispatch(group, new Runnable(){
        public void run() {
            HiLog.info(label, "task1 is running");  // 1
        }
    });
    dispatcher.asyncGroupDispatch(group, new Runnable(){
        public void run() {
            HiLog.info(label, "task2 is running");  // 2
        }
    });
    
    dispatcher.syncDispatchBarrier(new Runnable() {  
    public void run() {  
        HiLog.info(label, "barrier");  // 3
    }});  
    HiLog.info(label, "after syncDispatchBarrier");  // 4
}
​
// 1和2的执行顺序不定;3和4总是在1和2之后按顺序执行。
 
// 可能的执行结果:
// task1 is running
// task2 is running
// barrier
// after syncDispatchBarrier
 
// 另外一种执行结果:
// task2 is running
// task1 is running
// barrier
// after syncDispatchBarrier
   TaskDispatcher dispatcher = context.createParallelTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
   // 创建任务组。
   Group group = dispatcher.createDispatchGroup();
   // 将任务加入任务组,返回一个用于取消任务的接口。
   dispatcher.asyncGroupDispatch(group, new Runnable(){
       public void run() {
           HiLog.info(label, "task1 is running");  // 1
       }
   });
   dispatcher.asyncGroupDispatch(group, new Runnable(){
       public void run() {
           HiLog.info(label, "task2 is running");  // 2
       }
   });
    
   dispatcher.asyncDispatchBarrier(new Runnable() {  
       public void run() {  
           HiLog.info(label, "barrier");  // 3
       }
   });  
   HiLog.info(label, "after syncDispatchBarrier");  // 4
}
​
// 1和2的执行顺序不定,但总在3和4之前执行;4可能在3之前执行
 
// 可能的执行结果:
// task1 is running
// task2 is running
// after syncDispatchBarrier
// barrier 
 final int total = 10;
 final CountDownLatch latch = new CountDownLatch(total);
 final ArrayList<Long> indexList = new ArrayList<>(total);
 
 // 执行任务 total 次
 dispatcher.applyDispatch((index) -> {
     indexList.add(index);
     latch.countDown();
 }, total);
 
 // 设置任务超时
 try {    
     latch.await();
 } catch (InterruptedException exception) {
    HiLog.info(label, "latch exception");
 }
 HiLog.info(label, "list size matches, %{public}b", (total == indexList.size()));
 
// 执行结果:
// list size matches, true
上一篇 下一篇

猜你喜欢

热点阅读