1# 普通对象 2 3普通对象跨线程时通过拷贝形式传递,两个线程的对象内容一致,但是指向各自线程的隔离内存区间,被分配在各自线程的虚拟机本地堆(LocalHeap)。例如,Ecmascript262规范定义的Object、Array、Map等对象通过这种方式实现跨并发实例通信。通信过程如图所示: 4 5 6 7> **说明:** 8> 9> 普通类实例对象跨线程通过拷贝形式传递,只能传递数据,类实例上的方法会丢失。可以使用[@Sendable装饰器](arkts-sendable.md#sendable装饰器)标识为Sendable类,类实例对象跨线程传递后,可携带类方法。 10 11## 使用示例 12 13此处提供了一个传递普通对象的示例,具体实现如下: 14 15```ts 16// Test.ets 17// 自定义class TestA 18export class TestA { 19 constructor(name: string) { 20 this.name = name; 21 } 22 name: string = 'ClassA'; 23} 24``` 25 26```ts 27// Index.ets 28import { taskpool } from '@kit.ArkTS'; 29import { BusinessError } from '@kit.BasicServicesKit'; 30import { TestA } from './Test'; 31 32@Concurrent 33async function test1(arg: TestA) { 34 console.info("TestA name is: " + arg.name); 35} 36 37@Entry 38@Component 39struct Index { 40 @State message: string = 'Hello World'; 41 42 build() { 43 RelativeContainer() { 44 Text(this.message) 45 .id('HelloWorld') 46 .fontSize(50) 47 .fontWeight(FontWeight.Bold) 48 .alignRules({ 49 center: { anchor: '__container__', align: VerticalAlign.Center }, 50 middle: { anchor: '__container__', align: HorizontalAlign.Center } 51 }) 52 .onClick(() => { 53 // 1. 创建Test实例objA 54 let objA = new TestA("TestA"); 55 // 2. 创建任务task,将objA传递给该任务,objA非sendable对象,通过序列化传递给子线程 56 let task = new taskpool.Task(test1, objA); 57 // 3. 执行任务 58 taskpool.execute(task).then(() => { 59 console.info("taskpool: execute task success!"); 60 }).catch((e:BusinessError) => { 61 console.error(`taskpool: execute task: Code: ${e.code}, message: ${e.message}`); 62 }) 63 }) 64 } 65 .height('100%') 66 .width('100%') 67 } 68} 69```