• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 普通对象
2<!--Kit: ArkTS-->
3<!--Subsystem: CommonLibrary-->
4<!--Owner: @wang_zhaoyong-->
5<!--Designer: @weng-changcheng-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @ge-yafang-->
8
9普通对象跨线程时通过拷贝(序列化)形式传递,两个线程的对象内容一致,但指向各自线程的隔离内存区间,被分配在各自线程的虚拟机本地堆(LocalHeap)。序列化支持类型包括:除Symbol之外的基础类型、Date、String、RegExp、Array、Map、Set、Object(仅限简单对象,比如通过"{}"或者"new Object"创建,普通对象仅支持传递属性,不支持传递其原型及方法)、ArrayBuffer、TypedArray。通信过程如图所示:
10
11![deep_copy](figures/deep_copy.png)
12
13> **说明:**
14>
15> 普通类实例对象跨线程通过拷贝形式传递,只能传递数据,类方法会丢失。使用[@Sendable装饰器](arkts-sendable.md#sendable装饰器)标识为Sendable类后,类实例对象跨线程传递后,可携带类方法。
16
17## 使用示例
18
19此处提供了一个传递普通对象的示例,具体实现如下:
20
21```ts
22// Test.ets
23// 自定义class TestA
24export class TestA {
25  constructor(name: string) {
26    this.name = name;
27  }
28  name: string = 'ClassA';
29}
30```
31<!-- @[define_test_class](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/CommunicationObjects/entry/src/main/ets/managers/Test.ets) -->
32
33```ts
34// Index.ets
35import { taskpool } from '@kit.ArkTS';
36import { BusinessError } from '@kit.BasicServicesKit';
37import { TestA } from './Test';
38
39@Concurrent
40async function test1(arg: TestA) {
41  console.info("TestA name is: " + arg.name);
42}
43
44@Entry
45@Component
46struct Index {
47  @State message: string = 'Hello World';
48
49  build() {
50    RelativeContainer() {
51      Text(this.message)
52        .id('HelloWorld')
53        .fontSize(50)
54        .fontWeight(FontWeight.Bold)
55        .alignRules({
56          center: { anchor: '__container__', align: VerticalAlign.Center },
57          middle: { anchor: '__container__', align: HorizontalAlign.Center }
58        })
59        .onClick(() => {
60          // 1. 创建Test实例objA
61          let objA = new TestA("TestA");
62          // 2. 创建任务task,将objA传递给该任务,objA非sendable对象,通过序列化传递给子线程
63          let task = new taskpool.Task(test1, objA);
64          // 3. 执行任务
65          taskpool.execute(task).then(() => {
66            console.info("taskpool: execute task success!");
67          }).catch((e:BusinessError) => {
68            console.error(`taskpool: execute task: Code: ${e.code}, message: ${e.message}`);
69          })
70        })
71    }
72    .height('100%')
73    .width('100%')
74  }
75}
76```
77<!-- @[example_normal_obj](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/CommunicationObjects/entry/src/main/ets/managers/NormalObject.ets) -->