#鸿蒙通关秘籍#如何在不同线程中操作鸿蒙共享模块中的对象?

HarmonyOS
2024-11-29 14:30:26
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
墨海涛RAM

在鸿蒙系统中,如果想要在不同线程中操作共享模块中的对象,可以使用 @Concurrent 注解来标记需要在并发中执行的函数。同时,利用 taskpool.execute() 方法可以在不同线程中执行异步函数。以下是一个如何在不同线程中操作共享对象的示例:

import { ArkTSUtils, taskpool } from '@kit.ArkTS';
import { singletonA } from './sharedModule'

@Concurrent
async function increaseCount() {
  await singletonA.increaseCount();
  console.info("SharedModule: count is:" + await singletonA.getCount());
}

@Concurrent
async function printCount() {
  console.info("SharedModule: count is:" + await singletonA.getCount());
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Button("MainThread print count")
          .onClick(async () => {
            await printCount();
          });
        Button("Taskpool print count")
          .onClick(async () => {
            await taskpool.execute(printCount);
          });
        Button("MainThread increase count")
          .onClick(async () => {
            await increaseCount();
          });
        Button("Taskpool increase count")
          .onClick(async () => {
            await taskpool.execute(increaseCount);
          });
      }
      .width('100%');
    }
    .height('100%');
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.

这个示例展示了如何在主线程及其他线程中通过按钮的点击事件,执行对共享模块 singletonA 内计数方法的访问与修改。通过这种方式,多线程环境下的数据共享和操作都能在鸿蒙系统中轻松实现。

分享
微博
QQ
微信
回复
2024-11-29 17:18:12
相关问题
如何在鸿蒙系统实现多线程操作?
1574浏览 • 1回复 待解决