赞
踩
HarmonyOS App(JAVA)多线程任务分发器
打印时间,记录到编辑框textfield信息显示
同步分发,异步分发,异步延迟分发,分组任务分发,屏蔽任务分发,多次任务分发
参考代码注释
如果应用的业务逻辑比较复杂,可能需要创建多个线程来执行多个任务。这种情况下,代码复杂难以维护,任务与线程的交互也会更加繁杂。要解决此问题,开发者可以使用“TaskDispatcher”来分发不同的任务。
TaskDispatcher是一个任务分发器,它是Ability分发任务的基本接口,隐藏任务所在线程的实现细节。
为保证应用有更好的响应性,我们需要设计任务的优先级。在UI线程上运行的任务默认以高优先级运行,如果某个任务无需等待结果,则可以用低优先级。
优先级 | 详细描述 |
---|---|
HIGH | 最高任务优先级,比默认优先级、低优先级的任务有更高的几率得到执行。 |
DEFAULT | 默认任务优先级, 比低优先级的任务有更高的几率得到执行。 |
LOW | 低任务优先级,比高优先级、默认优先级的任务有更低的几率得到执行。 |
TaskDispatcher具有多种实现,每种实现对应不同的任务分发器。在分发任务时可以指定任务的优先级,由同一个任务分发器分发出的任务具有相同的优先级。系统提供的任务分发器有GlobalTaskDispatcher、ParallelTaskDispatcher、SerialTaskDispatcher 、SpecTaskDispatcher。
全局并发任务分发器,由Ability执行getGlobalTaskDispatcher()获取。适用于任务之间没有联系的情况。一个应用只有一个GlobalTaskDispatcher,它在程序结束时才被销毁。
并发任务分发器,由Ability执行createParallelTaskDispatcher()创建并返回。与GlobalTaskDispatcher不同的是,ParallelTaskDispatcher不具有全局唯一性,可以创建多个。开发者在创建或销毁dispatcher时,需要持有对应的对象引用 。
串行任务分发器,由Ability执行createSerialTaskDispatcher()创建并返回。由该分发器分发的所有的任务都是按顺序执行,但是执行这些任务的线程并不是固定的。如果要执行并行任务,应使用ParallelTaskDispatcher或者GlobalTaskDispatcher,而不是创建多个SerialTaskDispatcher。如果任务之间没有依赖,应使用GlobalTaskDispatcher来实现。它的创建和销毁由开发者自己管理,开发者在使用期间需要持有该对象引用。
专有任务分发器,绑定到专有线程上的任务分发器。目前已有的专有线程为UI线程,通过UITaskDispatcher进行任务分发。
UITaskDispatcher:绑定到应用主线程的专有任务分发器, 由Ability执行getUITaskDispatcher()创建并返回。 由该分发器分发的所有的任务都是在主线程上按顺序执行,它在应用程序结束时被销毁。
- <?xml version="1.0" encoding="utf-8"?>
- <DirectionalLayout
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:alignment="center"
- ohos:orientation="vertical">
-
- <Text
- ohos:id="$+id:text_helloworld"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="$graphic:background_ability_main"
- ohos:layout_alignment="horizontal_center"
- ohos:text="$string:mainability_HelloWorld"
- ohos:text_size="40vp"
- />
- <Button
- ohos:id="$+id:btn_tongbu"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#EB0BF647"
- ohos:layout_alignment="horizontal_center"
- ohos:text="同步分发"
- ohos:text_size="40vp"
- />
- <Button
- ohos:id="$+id:btn_yibu"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#EB3D5DFC"
- ohos:layout_alignment="horizontal_center"
- ohos:text="异步分发"
- ohos:text_size="40vp"
- />
- <Button
- ohos:id="$+id:btn_yibu_yanchi"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#EB0BF647"
- ohos:layout_alignment="horizontal_center"
- ohos:text="异步延迟分发"
- ohos:text_size="40vp"
- />
- <Button
- ohos:id="$+id:btn_fenzhu_task"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#EB3D5DFC"
- ohos:layout_alignment="horizontal_center"
- ohos:text="分组任务分发"
- ohos:text_size="40vp"
- />
- <Button
- ohos:id="$+id:btn_pingbi_task"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#EB0BF647"
- ohos:layout_alignment="horizontal_center"
- ohos:text="屏蔽任务分发"
- ohos:text_size="40vp"
- />
- <Button
- ohos:id="$+id:btn_duoci_task"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#EB3D5DFC"
- ohos:layout_alignment="horizontal_center"
- ohos:text="多次任务分发"
- ohos:text_size="40vp"
- />
-
- <Text
- ohos:id="$+id:text_label"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="$graphic:background_ability_main"
- ohos:layout_alignment="left"
- ohos:text="信息显示:"
- ohos:multiple_lines="true"
- ohos:text_size="20vp"
- />
- <TextField
- ohos:id="$+id:text_filed_info"
- ohos:height="300vp"
- ohos:background_element="#FC0A84EF"
- ohos:text="信息显示区域"
- ohos:width="350vp"
- ohos:hint=""
- ohos:margin="2vp"
- ohos:text_size="20vp"/>
- <Clock
- ohos:id="$+id:clock"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="#FF80EF66"
- ohos:layout_alignment="left"
-
- ohos:text_size="20vp"
- />
-
-
-
-
-
-
- </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;
- @Override
- public 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() {
- @Override
- public void onClick(Component component) {
- MoreTimesTask();
- }
- });
- btn_delay.setClickedListener(new Component.ClickedListener() {
- @Override
- public void onClick(Component component) {
- YibuDealyTask();
- }
- });
- btn_group.setClickedListener(new Component.ClickedListener() {
- @Override
- public void onClick(Component component) {
- YibuGroupTask();
- }
- });
- btn_pingbi.setClickedListener(new Component.ClickedListener() {
- @Override
- public void onClick(Component component) {
- PingBiTask();
- }
- });
- btn_yibu.setClickedListener(new Component.ClickedListener() {
- @Override
- public void onClick(Component component) {
- YibuTask();
- }
- });
- btn_tongbu.setClickedListener(new Component.ClickedListener() {
- @Override
- public 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() {
- @Override
- public 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() {
- @Override
- public 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() {
- @Override
- public 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() {
- @Override
- public 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() {
- @Override
- public 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() {
- @Override
- public 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() {
- @Override
- public void run() {
-
- HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
- }
-
- });
- dispatcher.asyncGroupDispatch(group, new Runnable() {
- @Override
- public void run() {
- HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
- }
-
- });
- dispatcher.asyncGroupDispatch(group, new Runnable() {
- @Override
- public 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 Consumer<Long>() {
- @Override
- public void accept(Long aLong) {
- getUITaskDispatcher().asyncDispatch(()->{
- textField.append(clock2.getText()+":多次任务分发线程启动"+aLong.toString()+"\n");
- });
- }
- },10); //执行10次
- }
-
- @Override
- public void onActive() {
- super.onActive();
- }
-
- @Override
- public void onForeground(Intent intent) {
- super.onForeground(intent);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。