HarmonyOS鸿蒙Next企业面试题之用过线程通信吗,线程是怎么进行通信的?
用过线程通信,线程是这样进行通信的,方法如下:
Worker 线程:用于后台任务处理,避免阻塞主线程。主线程和Worker线程通过postMessage和onmessage进行通信
TaskPool: 主要是使用Promise实现子线程和主线程通信的
import { taskpool } from '@kit.ArkTS';
//定义一个子线程
@Concurrent
function printArgs(args: number): number {
console.info("printArgs: " + args);
return args;
}
//定义一个子线程
@Concurrent
async function getInfo(username: string) {
let name=username+"_harmonyos";
console.info("getInfo: " + name);
return await new Promise<string>((resolve, reject) => {
setTimeout(() => {
resolve(name);
}, 2000);
})
}
//定义子线程返回一个数组
@Concurrent
async function getNewsList(): Promise<string[]> {
return await new Promise<string[]>((resolve, reject) => {
setTimeout(() => {
resolve(["news1", "news2", "news3"]);
}, 5000)
})
}
@Builder
export function TaskPoolPageBuilder() {
TaskPoolPage()
}
@Component
struct TaskPoolPage {
private pathStack=new NavPathStack()
executeTaskpool01(){
console.info("1");
taskpool.execute(printArgs, 100).then((value: Object) => { // 100: test number
console.info("taskpool result: " + value);
});
console.info("2");
}
executeTaskpool02(){
console.info("11");
taskpool.execute(getInfo, "zhangsan").then((value: Object) => {
console.info("taskpool result: " + value);
})
console.info("22");
}
executeTaskpool03(){
console.info("11");
taskpool.execute(getNewsList).then((value: Object) => {
console.info("taskpool result: " + JSON.stringify(value));
})
console.info("22");
}
build() {
NavDestination() {
Column({ space: 10 }) {
Button("TaskPool调用子线程")
.onClick(() => {
this.executeTaskpool01()
})
Button("TaskPool调用子线程2")
.onClick(() => {
this.executeTaskpool02()
}).margin({ left: 10, right: 10, top: 10, bottom: 10 })
Button("TaskPool调用子线程3")
.onClick(() => {
this.executeTaskpool03()
}).margin({ left: 10, right: 10, top: 10, bottom: 10 })
}
.width("100%")
.height("100%")
}
.title("TaskPool实现多线程")
.hideTitleBar(false)
.onReady((context: NavDestinationContext) => {
this.pathStack = context.pathStack
})
}
}
也可以使用eventHub实现
更多关于HarmonyOS鸿蒙Next企业面试题之用过线程通信吗,线程是怎么进行通信的?的实战教程也可以访问 https://www.itying.com/category-93-b0.html