#跟着坚果学鸿蒙#同步设置屏障任务:在任务组上设立任务执行屏障,同步等待任务组中的所有任 务执行完成,再执行指定任务。 说明 在全局并发任务分发器(GlobalTaskDispatcher)上同步设置任务屏障,将不会起到屏障 作用。 如下代码示例展示了如何同步设置屏障:

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 

asyncDispatchBarrier 异步设置屏障任务:在任务组上设立任务执行屏障后直接返回,指定任务将在任 务组中的所有任务执行完成后再执行。 说明 在全局并发任务分发器(GlobalTaskDispatcher)上异步设置任务屏障,将不会起到屏障 作用。可以使用并发任务分发器(ParallelTaskDispatcher)分离不同的任务组,达到微观 并行、宏观串行的行为。 如下代码示例展示了如何异步设置屏障:

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 

applyDispatch 执行多次任务:对指定任务执行多次。 如下代码示例展示了如何执行多次任务:

 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 

 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐