1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { worker } from '@kit.ArkTS'; 17import { taskpool } from '@kit.ArkTS'; 18 19// 步骤1: 定义并发函数,实现业务逻辑 20@Concurrent 21async function taskpoolFunc(num: number): Promise<number> { 22 // 根据业务逻辑实现相应的功能 23 let tmpNum: number = num + 100; 24 return tmpNum; 25} 26 27async function mainFunc(): Promise<void> { 28 // 步骤2: 创建任务并执行 29 let task1: taskpool.Task = new taskpool.Task(taskpoolFunc, 1); 30 let res1: number = await taskpool.execute(task1) as number; 31 let task2: taskpool.Task = new taskpool.Task(taskpoolFunc, res1); 32 let res2: number = await taskpool.execute(task2) as number; 33 // 步骤3: 对任务返回的结果进行操作 34 console.info('taskpool: task res1 is: ' + res1); 35 console.info('taskpool: task res2 is: ' + res2); 36} 37 38@Entry 39@Component 40struct Index { 41 @State message: string = 'Hello World'; 42 43 build() { 44 Row() { 45 Column() { 46 Text(this.message) 47 .fontSize(50) 48 .fontWeight(FontWeight.Bold) 49 .onClick(async () => { 50 mainFunc(); 51 let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker2.ts'); 52 w.onmessage = (): void => { 53 // 接收Worker子线程的结果 54 } 55 w.onerror = (): void => { 56 // 接收Worker子线程的错误信息 57 } 58 // 向Worker子线程发送Set消息 59 w.postMessage({ 'type': 0, 'data': 'data' }); 60 // 向Worker子线程发送Get消息 61 w.postMessage({ 'type': 1 }); 62 // ... 63 // 根据实际业务,选择时机以销毁线程 64 w.terminate(); 65 this.message = 'success'; 66 }) 67 } 68 .width('100%') 69 } 70 .height('100%') 71 } 72}