做小程序要有网站吗,酒店网站开发协议,免费域名网站创建,网站专题页怎么做HarmonyOS App(JAVA)多线程任务分发器
打印时间#xff0c;记录到编辑框textfield信息显示
同步分发#xff0c;异步分发#xff0c;异步延迟分发#xff0c;分组任务分发#xff0c;屏蔽任务分发#xff0c;多次任务分发
参考代码注释 场景介绍
如果应用的业务逻辑比…HarmonyOS App(JAVA)多线程任务分发器
打印时间记录到编辑框textfield信息显示
同步分发异步分发异步延迟分发分组任务分发屏蔽任务分发多次任务分发
参考代码注释 场景介绍
如果应用的业务逻辑比较复杂可能需要创建多个线程来执行多个任务。这种情况下代码复杂难以维护任务与线程的交互也会更加繁杂。要解决此问题开发者可以使用“TaskDispatcher”来分发不同的任务。
接口说明
TaskDispatcher是一个任务分发器它是Ability分发任务的基本接口隐藏任务所在线程的实现细节。
为保证应用有更好的响应性我们需要设计任务的优先级。在UI线程上运行的任务默认以高优先级运行如果某个任务无需等待结果则可以用低优先级。 表1 线程优先级介绍 优先级 详细描述 HIGH 最高任务优先级比默认优先级、低优先级的任务有更高的几率得到执行。 DEFAULT 默认任务优先级 比低优先级的任务有更高的几率得到执行。 LOW 低任务优先级比高优先级、默认优先级的任务有更低的几率得到执行。
TaskDispatcher具有多种实现每种实现对应不同的任务分发器。在分发任务时可以指定任务的优先级由同一个任务分发器分发出的任务具有相同的优先级。系统提供的任务分发器有GlobalTaskDispatcher、ParallelTaskDispatcher、SerialTaskDispatcher 、SpecTaskDispatcher。
GlobalTaskDispatcher 全局并发任务分发器由Ability执行getGlobalTaskDispatcher()获取。适用于任务之间没有联系的情况。一个应用只有一个GlobalTaskDispatcher它在程序结束时才被销毁。 TaskDispatcher globalTaskDispatcher getGlobalTaskDispatcher(TaskPriority.DEFAULT);ParallelTaskDispatcher 并发任务分发器由Ability执行createParallelTaskDispatcher()创建并返回。与GlobalTaskDispatcher不同的是ParallelTaskDispatcher不具有全局唯一性可以创建多个。开发者在创建或销毁dispatcher时需要持有对应的对象引用 。 String dispatcherName parallelTaskDispatcher;TaskDispatcher parallelTaskDispatcher createParallelTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);SerialTaskDispatcher 串行任务分发器由Ability执行createSerialTaskDispatcher()创建并返回。由该分发器分发的所有的任务都是按顺序执行但是执行这些任务的线程并不是固定的。如果要执行并行任务应使用ParallelTaskDispatcher或者GlobalTaskDispatcher而不是创建多个SerialTaskDispatcher。如果任务之间没有依赖应使用GlobalTaskDispatcher来实现。它的创建和销毁由开发者自己管理开发者在使用期间需要持有该对象引用。 String dispatcherName serialTaskDispatcher;TaskDispatcher serialTaskDispatcher createSerialTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);SpecTaskDispatcher 专有任务分发器绑定到专有线程上的任务分发器。目前已有的专有线程为UI线程通过UITaskDispatcher进行任务分发。 UITaskDispatcher绑定到应用主线程的专有任务分发器 由Ability执行getUITaskDispatcher()创建并返回。 由该分发器分发的所有的任务都是在主线程上按顺序执行它在应用程序结束时被销毁。 TaskDispatcher uiTaskDispatcher getUITaskDispatcher();
?xml version1.0 encodingutf-8?
DirectionalLayoutxmlns:ohoshttp://schemas.huawei.com/res/ohosohos:heightmatch_parentohos:widthmatch_parentohos:alignmentcenterohos:orientationverticalTextohos:id$id:text_helloworldohos:heightmatch_contentohos:widthmatch_contentohos:background_element$graphic:background_ability_mainohos:layout_alignmenthorizontal_centerohos:text$string:mainability_HelloWorldohos:text_size40vp/Buttonohos:id$id:btn_tongbuohos:heightmatch_contentohos:widthmatch_contentohos:background_element#EB0BF647ohos:layout_alignmenthorizontal_centerohos:text同步分发ohos:text_size40vp/Buttonohos:id$id:btn_yibuohos:heightmatch_contentohos:widthmatch_contentohos:background_element#EB3D5DFCohos:layout_alignmenthorizontal_centerohos:text异步分发ohos:text_size40vp/Buttonohos:id$id:btn_yibu_yanchiohos:heightmatch_contentohos:widthmatch_contentohos:background_element#EB0BF647ohos:layout_alignmenthorizontal_centerohos:text异步延迟分发ohos:text_size40vp/Buttonohos:id$id:btn_fenzhu_taskohos:heightmatch_contentohos:widthmatch_contentohos:background_element#EB3D5DFCohos:layout_alignmenthorizontal_centerohos:text分组任务分发ohos:text_size40vp/Buttonohos:id$id:btn_pingbi_taskohos:heightmatch_contentohos:widthmatch_contentohos:background_element#EB0BF647ohos:layout_alignmenthorizontal_centerohos:text屏蔽任务分发ohos:text_size40vp/Buttonohos:id$id:btn_duoci_taskohos:heightmatch_contentohos:widthmatch_contentohos:background_element#EB3D5DFCohos:layout_alignmenthorizontal_centerohos:text多次任务分发ohos:text_size40vp/Textohos:id$id:text_labelohos:heightmatch_contentohos:widthmatch_contentohos:background_element$graphic:background_ability_mainohos:layout_alignmentleftohos:text信息显示ohos:multiple_linestrueohos:text_size20vp/TextFieldohos:id$id:text_filed_infoohos:height300vpohos:background_element#FC0A84EFohos:text信息显示区域ohos:width350vpohos:hintohos:margin2vpohos:text_size20vp/Clockohos:id$id:clockohos:heightmatch_contentohos:widthmatch_contentohos:background_element#FF80EF66ohos:layout_alignmentleftohos:text_size20vp//DirectionalLayout
package com.example.myapplication.slice;import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.app.dispatcher.Group;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;import java.util.function.Consumer;public class MainAbilitySlice extends AbilitySlice {static final HiLogLabel label new HiLogLabel(HiLog.INFO,0x00101,shanshui);TextField textField;Clock clock2;Overridepublic void onStart(Intent intent) {super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);HiLog.info(label, hellocdtxw);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);System.out.println(hellocdtxw);Button btn_tongbu (Button) findComponentById(ResourceTable.Id_btn_tongbu);textField (TextField) findComponentById(ResourceTable.Id_text_filed_info);clock2 (Clock) findComponentById(ResourceTable.Id_clock);clock2.setFormatIn24HourMode(yyyy-MM-dd HH:mm:ss);Button btn_yibu (Button) findComponentById(ResourceTable.Id_btn_yibu);Button btn_delay (Button) findComponentById(ResourceTable.Id_btn_yibu_yanchi);Button btn_group (Button ) findComponentById(ResourceTable.Id_btn_fenzhu_task);Button btn_pingbi (Button) findComponentById(ResourceTable.Id_btn_pingbi_task);Button btn_more_time (Button) findComponentById(ResourceTable.Id_btn_duoci_task);btn_more_time.setClickedListener(new Component.ClickedListener() {Overridepublic void onClick(Component component) {MoreTimesTask();}});btn_delay.setClickedListener(new Component.ClickedListener() {Overridepublic void onClick(Component component) {YibuDealyTask();}});btn_group.setClickedListener(new Component.ClickedListener() {Overridepublic void onClick(Component component) {YibuGroupTask();}});btn_pingbi.setClickedListener(new Component.ClickedListener() {Overridepublic void onClick(Component component) {PingBiTask();}});btn_yibu.setClickedListener(new Component.ClickedListener() {Overridepublic void onClick(Component component) {YibuTask();}});btn_tongbu.setClickedListener(new Component.ClickedListener() {Overridepublic void onClick(Component component) {HiLog.info(label, hellocdtxw);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);System.out.println(hellocdtxw);TongBuTask();}});}/*同步分发任务,多线程阻塞模式会卡主界面不常用*/public void TongBuTask(){TaskDispatcher dispatcher getGlobalTaskDispatcher(TaskPriority.DEFAULT);String time_str clock2.getText();textField.append(time_str:同步线程启动\n);dispatcher.syncDispatch(new Runnable() {Overridepublic void run() {try{//getUITaskDispatcher().syncDispatch(()-{// textField.append(clock2.getText():task1:Thread.currentThread().getName());//});Thread.sleep(1000);}catch (InterruptedException e){//getUITaskDispatcher().syncDispatch(()-{// textField.append(clock2.getText()任务失败);// });}}});dispatcher.syncDispatch(new Runnable() {Overridepublic void run() {try{//getUITaskDispatcher().syncDispatch(()-{// textField.append(clock2.getText():task1:Thread.currentThread().getName());//});Thread.sleep(1000);}catch (InterruptedException e){//getUITaskDispatcher().syncDispatch(()-{// textField.append(clock2.getText()任务失败);// });}}});dispatcher.syncDispatch(new Runnable() {Overridepublic void run() {try{//getUITaskDispatcher().syncDispatch(()-{// textField.append(clock2.getText():task1:Thread.currentThread().getName());//});Thread.sleep(1000);}catch (InterruptedException e){//getUITaskDispatcher().syncDispatch(()-{// textField.append(clock2.getText()任务失败);// });}}});}//异步模式鸿蒙系统app多线程public void YibuTask(){TaskDispatcher dispatcher getGlobalTaskDispatcher(TaskPriority.DEFAULT);String time_str clock2.getText();textField.append(time_str:异步线程启动\n);dispatcher.asyncDispatch(new Runnable() {Overridepublic void run() {try{getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText():task1:Thread.currentThread().getName()\n);});Thread.sleep(1000);}catch (InterruptedException e){getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText()任务失败);});}}});dispatcher.asyncDispatch(new Runnable() {Overridepublic void run() {try{getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText():task2:Thread.currentThread().getName()\n);});Thread.sleep(1000);}catch (InterruptedException e){getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText()任务失败);});}}});dispatcher.asyncDispatch(new Runnable() {Overridepublic void run() {try{getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText():task3:Thread.currentThread().getName()\n);});Thread.sleep(1000);}catch (InterruptedException e){getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText()任务失败);});}}});}//异步延迟任务分发public void YibuDealyTask(){TaskDispatcher dispatcher getGlobalTaskDispatcher(TaskPriority.DEFAULT);String time_str clock2.getText();dispatcher.delayDispatch(()- {getUITaskDispatcher().asyncDispatch(()-{textField.append(time_str:异步延迟任务分发线程启动\n);});},1000);}//异步分组任务分发public void YibuGroupTask(){TaskDispatcher dispatcher getGlobalTaskDispatcher(TaskPriority.DEFAULT);String time_str clock2.getText();Group group dispatcher.createDispatchGroup();dispatcher.asyncGroupDispatch(group, new Runnable() {Overridepublic void run() {HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}});dispatcher.asyncGroupDispatch(group, new Runnable() {Overridepublic void run() {HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}});dispatcher.asyncGroupDispatch(group, new Runnable() {Overridepublic void run() {HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}});}//屏蔽任务分发public void PingBiTask(){TaskDispatcher dispatcher createParallelTaskDispatcher(Dispatcher,TaskPriority.DEFAULT);Group group dispatcher.createDispatchGroup();dispatcher.asyncGroupDispatch(group,()-{try{Thread.sleep(1000);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}catch (InterruptedException ex){}});dispatcher.asyncGroupDispatch(group,()-{try{Thread.sleep(1000);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}catch (InterruptedException ex){}});dispatcher.asyncDispatchBarrier(()-{try{Thread.sleep(1000);getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText():屏蔽任务分发线程启动\n);});}catch (InterruptedException ex){}});dispatcher.asyncGroupDispatch(group,()-{try{Thread.sleep(1000);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}catch (InterruptedException ex){}});dispatcher.asyncGroupDispatch(group,()-{try{Thread.sleep(1000);HiLog.info(label, %{public}s World %d, hellocdtxw, 3);}catch (InterruptedException ex){}});dispatcher.asyncDispatchBarrier(()-{try{Thread.sleep(1000);getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText():屏蔽任务分发线程启动\n);});}catch (InterruptedException ex){}});}public void MoreTimesTask(){getGlobalTaskDispatcher(TaskPriority.DEFAULT).applyDispatch(new ConsumerLong() {Overridepublic void accept(Long aLong) {getUITaskDispatcher().asyncDispatch(()-{textField.append(clock2.getText():多次任务分发线程启动aLong.toString()\n);});}},10); //执行10次}Overridepublic void onActive() {super.onActive();}Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}
}