```ts
class Task {
static run(args) {
// Do some independent task
}
}
let thread = new Thread(() => {
let result = Task.run(args)
// deal with result
})
```
ArkTS写法
```ts
import taskpool from '@ohos.taskpool'
@Concurrent
function run(args) {
// Do some independent task
}
let task = new taskpool.Task(run, args)
taskpool.execute(task).then((ret) => {
// Return result
})
```
场景二:主线程将创建的类对象实例在子线程使用
代码示例:
共享内存写法
```ts
class Material {
action(args) {
// Do some independent task
}
}
let material = new Material()
let thread = new Thread(() => {
let result = material.action(args)
// deal with result
})
```
ArkTS写法
```ts
import taskpool from '@ohos.taskpool'
@Concurrent
function runner(material: Material) {
return material.action();
}
@Sendable
class Material {
action(args) {
// Do some independent task
}
}
let material = new Material()
taskpool.execute(runner, material).then((ret) => {
// Return result
})
```
场景三:主线程将独立的耗时任务放到子线程执行
代码示例:
```ts
class Task {
run(args) {
// Do some independent task
task.result = true
}
}
let task = new Task()
let thread = new Thread(() => {
let result = task.run(args)
// deal with result
})
```
ArkTS写法
```ts
import taskpool from '@ohos.taskpool'
@Concurrent
function runner(task) {
task.run()
}
@Sendable
class Task {
run(args) {
// Do some independent task
return true
}
}
let task = new Task()
taskpool.execute(runner, task).then((ret) => {
task.result = ret
})
```
场景四:子线程主动更新主线程状态
代码示例:
```ts
class Task {
run(args) {
// Do some independent task
runOnUiThread(() => {
UpdateUI(result)
})
}
}
let task = new Task()
let thread = new Thread(() => {
let result = task.run(args)
// deal with result
})
```
ArkTS写法
```ts
import taskpool from '@ohos.taskpool'
@Concurrent
function runner(task) {
task.run()
}
@Sendable
class Task {
run(args) {
// Do some independent task
taskpool.Task.sendData(result)
}
}
let task = new Task()
let run = new taskpool.Task(runner, task)
run.onReceiveData((result) => {
UpdateUI(result)
})
taskpool.execute(run).then((ret) => {
// Return result
})
```
场景五:子线程同步调用主线程的接口
代码示例:
```ts
class SdkU3d {
static getInst() {
return SdkMgr.getInst();
}
getPropStr(str: string) {
return xx;
}
}
let thread = new Thread(() => {
// 游戏线程
let sdk = SdkU3d.getInst()
let ret = sdk.getPropStr("xx")
})
```
ArkTS写法
```ts
// 主线程
import worker from '@ohos.worker'
class SdkU3d {
static getInst() {
return SdkMgr.getInst();
}
getPropStr(str: string) {}
}
const workerInstance = new
worker.ThreadWorker("xx/worker.ts");
let sdk = SdkU3d.getInst()
workerInstance.registerGlobalCallObject ("instance_xx", sdk);
workerInstance.postMessage("start");
// 游戏worker线程
import worker from '@ohos.worker'
const mainPort = worker.workerPort;
mainPort.onmessage = (e: MessageEvents): void => {
let ret = mainPort.callGlobalCallObjectMethod(
"instance_xx", "getPropStr", "xx");
}
```