当前位置:   article > 正文

30.HarmonyOS App(JAVA)鸿蒙系统app多线程任务分发器

30.HarmonyOS App(JAVA)鸿蒙系统app多线程任务分发器

HarmonyOS App(JAVA)多线程任务分发器

打印时间,记录到编辑框textfield信息显示

同步分发,异步分发,异步延迟分发,分组任务分发,屏蔽任务分发,多次任务分发

参考代码注释

场景介绍

如果应用的业务逻辑比较复杂,可能需要创建多个线程来执行多个任务。这种情况下,代码复杂难以维护,任务与线程的交互也会更加繁杂。要解决此问题,开发者可以使用“TaskDispatcher”来分发不同的任务。

接口说明

TaskDispatcher是一个任务分发器,它是Ability分发任务的基本接口,隐藏任务所在线程的实现细节。

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

表1 线程优先级介绍

优先级

详细描述

HIGH

最高任务优先级,比默认优先级、低优先级的任务有更高的几率得到执行。

DEFAULT

默认任务优先级, 比低优先级的任务有更高的几率得到执行。

LOW

低任务优先级,比高优先级、默认优先级的任务有更低的几率得到执行。

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

  • GlobalTaskDispatcher

    全局并发任务分发器,由Ability执行getGlobalTaskDispatcher()获取。适用于任务之间没有联系的情况。一个应用只有一个GlobalTaskDispatcher,它在程序结束时才被销毁。

     
      
    1. TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
  • ParallelTaskDispatcher

    并发任务分发器,由Ability执行createParallelTaskDispatcher()创建并返回。与GlobalTaskDispatcher不同的是,ParallelTaskDispatcher不具有全局唯一性,可以创建多个。开发者在创建或销毁dispatcher时,需要持有对应的对象引用 。

     
      
    1. String dispatcherName = "parallelTaskDispatcher";
    2. TaskDispatcher parallelTaskDispatcher = createParallelTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
  • SerialTaskDispatcher

    串行任务分发器,由Ability执行createSerialTaskDispatcher()创建并返回。由该分发器分发的所有的任务都是按顺序执行,但是执行这些任务的线程并不是固定的。如果要执行并行任务,应使用ParallelTaskDispatcher或者GlobalTaskDispatcher,而不是创建多个SerialTaskDispatcher。如果任务之间没有依赖,应使用GlobalTaskDispatcher来实现。它的创建和销毁由开发者自己管理,开发者在使用期间需要持有该对象引用。

     
      
    1. String dispatcherName = "serialTaskDispatcher";
    2. TaskDispatcher serialTaskDispatcher = createSerialTaskDispatcher(dispatcherName, TaskPriority.DEFAULT);
  • SpecTaskDispatcher

    专有任务分发器,绑定到专有线程上的任务分发器。目前已有的专有线程为UI线程,通过UITaskDispatcher进行任务分发。

    UITaskDispatcher:绑定到应用主线程的专有任务分发器, 由Ability执行getUITaskDispatcher()创建并返回。 由该分发器分发的所有的任务都是在主线程上按顺序执行,它在应用程序结束时被销毁。

     
      
    1. TaskDispatcher uiTaskDispatcher = getUITaskDispatcher();
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3. xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4. ohos:height="match_parent"
  5. ohos:width="match_parent"
  6. ohos:alignment="center"
  7. ohos:orientation="vertical">
  8. <Text
  9. ohos:id="$+id:text_helloworld"
  10. ohos:height="match_content"
  11. ohos:width="match_content"
  12. ohos:background_element="$graphic:background_ability_main"
  13. ohos:layout_alignment="horizontal_center"
  14. ohos:text="$string:mainability_HelloWorld"
  15. ohos:text_size="40vp"
  16. />
  17. <Button
  18. ohos:id="$+id:btn_tongbu"
  19. ohos:height="match_content"
  20. ohos:width="match_content"
  21. ohos:background_element="#EB0BF647"
  22. ohos:layout_alignment="horizontal_center"
  23. ohos:text="同步分发"
  24. ohos:text_size="40vp"
  25. />
  26. <Button
  27. ohos:id="$+id:btn_yibu"
  28. ohos:height="match_content"
  29. ohos:width="match_content"
  30. ohos:background_element="#EB3D5DFC"
  31. ohos:layout_alignment="horizontal_center"
  32. ohos:text="异步分发"
  33. ohos:text_size="40vp"
  34. />
  35. <Button
  36. ohos:id="$+id:btn_yibu_yanchi"
  37. ohos:height="match_content"
  38. ohos:width="match_content"
  39. ohos:background_element="#EB0BF647"
  40. ohos:layout_alignment="horizontal_center"
  41. ohos:text="异步延迟分发"
  42. ohos:text_size="40vp"
  43. />
  44. <Button
  45. ohos:id="$+id:btn_fenzhu_task"
  46. ohos:height="match_content"
  47. ohos:width="match_content"
  48. ohos:background_element="#EB3D5DFC"
  49. ohos:layout_alignment="horizontal_center"
  50. ohos:text="分组任务分发"
  51. ohos:text_size="40vp"
  52. />
  53. <Button
  54. ohos:id="$+id:btn_pingbi_task"
  55. ohos:height="match_content"
  56. ohos:width="match_content"
  57. ohos:background_element="#EB0BF647"
  58. ohos:layout_alignment="horizontal_center"
  59. ohos:text="屏蔽任务分发"
  60. ohos:text_size="40vp"
  61. />
  62. <Button
  63. ohos:id="$+id:btn_duoci_task"
  64. ohos:height="match_content"
  65. ohos:width="match_content"
  66. ohos:background_element="#EB3D5DFC"
  67. ohos:layout_alignment="horizontal_center"
  68. ohos:text="多次任务分发"
  69. ohos:text_size="40vp"
  70. />
  71. <Text
  72. ohos:id="$+id:text_label"
  73. ohos:height="match_content"
  74. ohos:width="match_content"
  75. ohos:background_element="$graphic:background_ability_main"
  76. ohos:layout_alignment="left"
  77. ohos:text="信息显示:"
  78. ohos:multiple_lines="true"
  79. ohos:text_size="20vp"
  80. />
  81. <TextField
  82. ohos:id="$+id:text_filed_info"
  83. ohos:height="300vp"
  84. ohos:background_element="#FC0A84EF"
  85. ohos:text="信息显示区域"
  86. ohos:width="350vp"
  87. ohos:hint=""
  88. ohos:margin="2vp"
  89. ohos:text_size="20vp"/>
  90. <Clock
  91. ohos:id="$+id:clock"
  92. ohos:height="match_content"
  93. ohos:width="match_content"
  94. ohos:background_element="#FF80EF66"
  95. ohos:layout_alignment="left"
  96. ohos:text_size="20vp"
  97. />
  98. </DirectionalLayout>
  1. package com.example.myapplication.slice;
  2. import com.example.myapplication.ResourceTable;
  3. import ohos.aafwk.ability.AbilitySlice;
  4. import ohos.aafwk.content.Intent;
  5. import ohos.agp.components.*;
  6. import ohos.app.dispatcher.Group;
  7. import ohos.app.dispatcher.TaskDispatcher;
  8. import ohos.app.dispatcher.task.TaskPriority;
  9. import ohos.hiviewdfx.HiLog;
  10. import ohos.hiviewdfx.HiLogLabel;
  11. import java.util.function.Consumer;
  12. public class MainAbilitySlice extends AbilitySlice {
  13. static final HiLogLabel label = new HiLogLabel(HiLog.INFO,0x00101,"shanshui");
  14. TextField textField;
  15. Clock clock2;
  16. @Override
  17. public void onStart(Intent intent) {
  18. super.onStart(intent);
  19. super.setUIContent(ResourceTable.Layout_ability_main);
  20. HiLog.info(label, "hellocdtxw");
  21. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  22. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  23. System.out.println("hellocdtxw");
  24. Button btn_tongbu = (Button) findComponentById(ResourceTable.Id_btn_tongbu);
  25. textField = (TextField) findComponentById(ResourceTable.Id_text_filed_info);
  26. clock2 = (Clock) findComponentById(ResourceTable.Id_clock);
  27. clock2.setFormatIn24HourMode("yyyy-MM-dd HH:mm:ss");
  28. Button btn_yibu = (Button) findComponentById(ResourceTable.Id_btn_yibu);
  29. Button btn_delay = (Button) findComponentById(ResourceTable.Id_btn_yibu_yanchi);
  30. Button btn_group = (Button ) findComponentById(ResourceTable.Id_btn_fenzhu_task);
  31. Button btn_pingbi = (Button) findComponentById(ResourceTable.Id_btn_pingbi_task);
  32. Button btn_more_time = (Button) findComponentById(ResourceTable.Id_btn_duoci_task);
  33. btn_more_time.setClickedListener(new Component.ClickedListener() {
  34. @Override
  35. public void onClick(Component component) {
  36. MoreTimesTask();
  37. }
  38. });
  39. btn_delay.setClickedListener(new Component.ClickedListener() {
  40. @Override
  41. public void onClick(Component component) {
  42. YibuDealyTask();
  43. }
  44. });
  45. btn_group.setClickedListener(new Component.ClickedListener() {
  46. @Override
  47. public void onClick(Component component) {
  48. YibuGroupTask();
  49. }
  50. });
  51. btn_pingbi.setClickedListener(new Component.ClickedListener() {
  52. @Override
  53. public void onClick(Component component) {
  54. PingBiTask();
  55. }
  56. });
  57. btn_yibu.setClickedListener(new Component.ClickedListener() {
  58. @Override
  59. public void onClick(Component component) {
  60. YibuTask();
  61. }
  62. });
  63. btn_tongbu.setClickedListener(new Component.ClickedListener() {
  64. @Override
  65. public void onClick(Component component) {
  66. HiLog.info(label, "hellocdtxw");
  67. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  68. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  69. System.out.println("hellocdtxw");
  70. TongBuTask();
  71. }
  72. });
  73. }
  74. /*
  75. 同步分发任务,多线程,阻塞模式,会卡主界面,不常用
  76. */
  77. public void TongBuTask()
  78. {
  79. TaskDispatcher dispatcher =
  80. getGlobalTaskDispatcher(TaskPriority.DEFAULT);
  81. String time_str = clock2.getText();
  82. textField.append(time_str+":同步线程启动\n");
  83. dispatcher.syncDispatch(new Runnable() {
  84. @Override
  85. public void run() {
  86. try
  87. {
  88. //getUITaskDispatcher().syncDispatch(()->{
  89. // textField.append(clock2.getText()+":task1:"+Thread.currentThread().getName());
  90. //});
  91. Thread.sleep(1000);
  92. }
  93. catch (InterruptedException e)
  94. {
  95. //getUITaskDispatcher().syncDispatch(()->{
  96. // textField.append(clock2.getText()+"任务失败");
  97. // });
  98. }
  99. }
  100. });
  101. dispatcher.syncDispatch(new Runnable() {
  102. @Override
  103. public void run() {
  104. try
  105. {
  106. //getUITaskDispatcher().syncDispatch(()->{
  107. // textField.append(clock2.getText()+":task1:"+Thread.currentThread().getName());
  108. //});
  109. Thread.sleep(1000);
  110. }
  111. catch (InterruptedException e)
  112. {
  113. //getUITaskDispatcher().syncDispatch(()->{
  114. // textField.append(clock2.getText()+"任务失败");
  115. // });
  116. }
  117. }
  118. });
  119. dispatcher.syncDispatch(new Runnable() {
  120. @Override
  121. public void run() {
  122. try
  123. {
  124. //getUITaskDispatcher().syncDispatch(()->{
  125. // textField.append(clock2.getText()+":task1:"+Thread.currentThread().getName());
  126. //});
  127. Thread.sleep(1000);
  128. }
  129. catch (InterruptedException e)
  130. {
  131. //getUITaskDispatcher().syncDispatch(()->{
  132. // textField.append(clock2.getText()+"任务失败");
  133. // });
  134. }
  135. }
  136. });
  137. }
  138. //异步模式,鸿蒙系统app多线程
  139. public void YibuTask()
  140. {
  141. TaskDispatcher dispatcher =
  142. getGlobalTaskDispatcher(TaskPriority.DEFAULT);
  143. String time_str = clock2.getText();
  144. textField.append(time_str+":异步线程启动\n");
  145. dispatcher.asyncDispatch(new Runnable() {
  146. @Override
  147. public void run() {
  148. try
  149. {
  150. getUITaskDispatcher().asyncDispatch(()->{
  151. textField.append(clock2.getText()+":task1:"+Thread.currentThread().getName()+"\n");
  152. });
  153. Thread.sleep(1000);
  154. }
  155. catch (InterruptedException e)
  156. {
  157. getUITaskDispatcher().asyncDispatch(()->{
  158. textField.append(clock2.getText()+"任务失败");
  159. });
  160. }
  161. }
  162. });
  163. dispatcher.asyncDispatch(new Runnable() {
  164. @Override
  165. public void run() {
  166. try
  167. {
  168. getUITaskDispatcher().asyncDispatch(()->{
  169. textField.append(clock2.getText()+":task2:"+Thread.currentThread().getName()+"\n");
  170. });
  171. Thread.sleep(1000);
  172. }
  173. catch (InterruptedException e)
  174. {
  175. getUITaskDispatcher().asyncDispatch(()->{
  176. textField.append(clock2.getText()+"任务失败");
  177. });
  178. }
  179. }
  180. });
  181. dispatcher.asyncDispatch(new Runnable() {
  182. @Override
  183. public void run() {
  184. try
  185. {
  186. getUITaskDispatcher().asyncDispatch(()->{
  187. textField.append(clock2.getText()+":task3:"+Thread.currentThread().getName()+"\n");
  188. });
  189. Thread.sleep(1000);
  190. }
  191. catch (InterruptedException e)
  192. {
  193. getUITaskDispatcher().asyncDispatch(()->{
  194. textField.append(clock2.getText()+"任务失败");
  195. });
  196. }
  197. }
  198. });
  199. }
  200. //异步延迟任务分发
  201. public void YibuDealyTask()
  202. {
  203. TaskDispatcher dispatcher =
  204. getGlobalTaskDispatcher(TaskPriority.DEFAULT);
  205. String time_str = clock2.getText();
  206. dispatcher.delayDispatch(()-> {
  207. getUITaskDispatcher().asyncDispatch(()->{
  208. textField.append(time_str+":异步延迟任务分发线程启动\n");
  209. });
  210. },1000);
  211. }
  212. //异步分组任务分发
  213. public void YibuGroupTask()
  214. {
  215. TaskDispatcher dispatcher =
  216. getGlobalTaskDispatcher(TaskPriority.DEFAULT);
  217. String time_str = clock2.getText();
  218. Group group = dispatcher.createDispatchGroup();
  219. dispatcher.asyncGroupDispatch(group, new Runnable() {
  220. @Override
  221. public void run() {
  222. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  223. }
  224. });
  225. dispatcher.asyncGroupDispatch(group, new Runnable() {
  226. @Override
  227. public void run() {
  228. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  229. }
  230. });
  231. dispatcher.asyncGroupDispatch(group, new Runnable() {
  232. @Override
  233. public void run() {
  234. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  235. }
  236. });
  237. }
  238. //屏蔽任务分发
  239. public void PingBiTask()
  240. {
  241. TaskDispatcher dispatcher =
  242. createParallelTaskDispatcher("Dispatcher",
  243. TaskPriority.DEFAULT);
  244. Group group = dispatcher.createDispatchGroup();
  245. dispatcher.asyncGroupDispatch(group,()->{
  246. try
  247. {
  248. Thread.sleep(1000);
  249. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  250. }
  251. catch (InterruptedException ex)
  252. {
  253. }
  254. });
  255. dispatcher.asyncGroupDispatch(group,()->{
  256. try
  257. {
  258. Thread.sleep(1000);
  259. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  260. }
  261. catch (InterruptedException ex)
  262. {
  263. }
  264. });
  265. dispatcher.asyncDispatchBarrier(()->{
  266. try
  267. {
  268. Thread.sleep(1000);
  269. getUITaskDispatcher().asyncDispatch(()->{
  270. textField.append(clock2.getText()+":屏蔽任务分发线程启动\n");
  271. });
  272. }
  273. catch (InterruptedException ex)
  274. {
  275. }
  276. });
  277. dispatcher.asyncGroupDispatch(group,()->{
  278. try
  279. {
  280. Thread.sleep(1000);
  281. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  282. }
  283. catch (InterruptedException ex)
  284. {
  285. }
  286. });
  287. dispatcher.asyncGroupDispatch(group,()->{
  288. try
  289. {
  290. Thread.sleep(1000);
  291. HiLog.info(label, "%{public}s World %d", "hellocdtxw", 3);
  292. }
  293. catch (InterruptedException ex)
  294. {
  295. }
  296. });
  297. dispatcher.asyncDispatchBarrier(()->{
  298. try
  299. {
  300. Thread.sleep(1000);
  301. getUITaskDispatcher().asyncDispatch(()->{
  302. textField.append(clock2.getText()+":屏蔽任务分发线程启动\n");
  303. });
  304. }
  305. catch (InterruptedException ex)
  306. {
  307. }
  308. });
  309. }
  310. public void MoreTimesTask()
  311. {
  312. getGlobalTaskDispatcher(TaskPriority.DEFAULT).applyDispatch(new Consumer<Long>() {
  313. @Override
  314. public void accept(Long aLong) {
  315. getUITaskDispatcher().asyncDispatch(()->{
  316. textField.append(clock2.getText()+":多次任务分发线程启动"+aLong.toString()+"\n");
  317. });
  318. }
  319. },10); //执行10
  320. }
  321. @Override
  322. public void onActive() {
  323. super.onActive();
  324. }
  325. @Override
  326. public void onForeground(Intent intent) {
  327. super.onForeground(intent);
  328. }
  329. }

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/262471
推荐阅读
相关标签
  

闽ICP备14008679号