1# 业务模块并发加载场景 2<!--Kit: ArkTS--> 3<!--Subsystem: CommonLibrary--> 4<!--Owner: @lijiamin2025--> 5<!--Designer: @weng-changcheng--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @ge-yafang--> 8 9在应用启动时,多个业务模块需要加载,例如地图应用中的定位、打车、导航等模块。如果全部在UI主线程初始化,会严重影响应用冷启动时间。此时,应在不同子线程中并行加载这些模块,以降低启动耗时。 10 11通过使用ArkTS提供的TaskPool能力,可以将不同的业务初始化任务移到子线程中。业务模块可通过下沉C++实现为[NativeBinding对象](transferabled-object.md)或在ArkTS层定义为[Sendable对象](arkts-sendable.md),从而将初始化的模块返回给UI主线程调用,实现如下。 12 131. 各业务功能(SDK)模块定义(这里以使用Sendable对象为例)。 14 计算器业务模块定义如下: 15 16 ```ts 17 // sdk/Calculator.ets 18 import { collections } from '@kit.ArkTS'; 19 20 @Sendable 21 export class Calculator { 22 history?: collections.Array<collections.Array<string>>; 23 totalCount: number = 0; 24 25 static init(): Calculator { 26 let calc = new Calculator(); 27 calc.totalCount = 0; 28 calc.history = collections.Array.create(calc.totalCount, collections.Array.create(2, "")); 29 return calc; 30 } 31 32 add(a: number, b: number) { 33 let result = a + b; 34 this.newCalc(`${a} + ${b}`, `${result}`); 35 return result; 36 } 37 38 sub(a: number, b: number) { 39 let result = a - b; 40 this.newCalc(`${a} - ${b}`, `${result}`); 41 return result; 42 } 43 44 mul(a: number, b: number) { 45 let result = a * b; 46 this.newCalc(`${a} * ${b}`, `${result}`); 47 return result; 48 } 49 50 div(a: number, b: number) { 51 let result = a / b; 52 this.newCalc(`${a} / ${b}`, `${result}`); 53 return result; 54 } 55 56 getHistory(): collections.Array<collections.Array<string>> { 57 return this.history!; 58 } 59 60 showHistory() { 61 for (let i = 0; i < this.totalCount; i++) { 62 console.info(`${i}: ${this.history![i][0]} = ${this.history![i][1]}`); 63 } 64 } 65 66 private newCalc(opt: string, ret: string) { 67 let newRecord = new collections.Array<string>(opt, ret); 68 this.totalCount = this.history!.unshift(newRecord); 69 } 70 } 71 ``` 72 <!-- @[define_calculator_module](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/PracticalCases/entry/src/main/ets/sdk/Calculator.ets) --> 73 74 定时器业务模块的定义如下: 75 76 ```ts 77 // sdk/TimerSdk.ets 78 @Sendable 79 export class TimerSdk { 80 static init(): TimerSdk { 81 let timer = new TimerSdk(); 82 return timer; 83 } 84 85 async countDown(time: number) { 86 return new Promise((resolve: (value: boolean) => void) => { 87 setTimeout(() => { 88 resolve(true); 89 }, time); 90 }) 91 } 92 } 93 ``` 94 <!-- @[define_timer_module](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/PracticalCases/entry/src/main/ets/sdk/TimerSdk.ets) --> 95 962. 在UI主线程触发各业务模块分发到子线程,加载完成后在UI主线程使用,示例如下: 97 98 ```ts 99 // Index.ets 100 import { Calculator } from '../sdk/Calculator'; 101 import { TimerSdk } from '../sdk/TimerSdk'; 102 import { taskpool } from '@kit.ArkTS'; 103 104 @Concurrent 105 function initCalculator(): Calculator { 106 return Calculator.init(); 107 } 108 109 @Concurrent 110 function initTimerSdk(): TimerSdk { 111 return TimerSdk.init(); 112 } 113 114 @Entry 115 @Component 116 struct Index { 117 calc?: Calculator 118 timer?: TimerSdk 119 120 aboutToAppear(): void { 121 taskpool.execute(initCalculator).then((ret) => { 122 this.calc = ret as Calculator; 123 }) 124 taskpool.execute(initTimerSdk).then((ret) => { 125 this.timer = ret as TimerSdk; 126 }) 127 } 128 129 build() { 130 Row() { 131 Column() { 132 Text("calculate add") 133 .id('add') 134 .fontSize(50) 135 .fontWeight(FontWeight.Bold) 136 .alignRules({ 137 center: { anchor: '__container__', align: VerticalAlign.Center }, 138 middle: { anchor: '__container__', align: HorizontalAlign.Center } 139 }) 140 .onClick(async () => { 141 let result = this.calc?.add(1, 2); 142 console.info(`Result is ${result}`); 143 }) 144 Text("show history") 145 .id('show') 146 .fontSize(50) 147 .fontWeight(FontWeight.Bold) 148 .alignRules({ 149 center: { anchor: '__container__', align: VerticalAlign.Center }, 150 middle: { anchor: '__container__', align: HorizontalAlign.Center } 151 }) 152 .onClick(async () => { 153 this.calc?.showHistory(); 154 }) 155 Text("countdown") 156 .id('get') 157 .fontSize(50) 158 .fontWeight(FontWeight.Bold) 159 .alignRules({ 160 center: { anchor: '__container__', align: VerticalAlign.Center }, 161 middle: { anchor: '__container__', align: HorizontalAlign.Center } 162 }) 163 .onClick(async () => { 164 console.info(`Timer start`); 165 await this.timer?.countDown(1000); 166 console.info(`Timer end`); 167 }) 168 } 169 .width('100%') 170 } 171 .height('100%') 172 } 173 } 174 ``` 175 <!-- @[distribute_child_thread](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/PracticalCases/entry/src/main/ets/managers/ConcurrentLoadingModulesGuide.ets) --> 176