如何在Worker中开启多级子线程
=================

在Worker中开启多级子线程，具体可参考如下示例代码：

import { ErrorEvent, MessageEvents, worker } from '@kit.ArkTS';

const workerInstance = new worker.ThreadWorker('entry/ets/pages/Worker.ets');

_// The main thread passes information to the worker thread_
workerInstance.postMessage('123');

_// The main thread receives worker thread information_
workerInstance.onmessage = (e: MessageEvents): void => {
 _ // Data: Information sent by the Worker thread_
  let data: string = e.data;
  console.info(\`main thread onmessage, data:${data}\`);
  const workerInstance1 = new worker.ThreadWorker('entry/ets/pages/Work.ets');
  workerInstance1.postMessage('123');
  workerInstance1.onmessage = (e: MessageEvents): void => {
   _ // data：Information sent by worker threads_
    let data1: string = e.data;
    console.info(\`main thread onmessage1, data:${data1}\`);
  _  // Destroy Worker object_
    workerInstance1.terminate();
  }
 _ // After calling terminate, execute onexit_
  workerInstance1.onexit = (code) => {
    console.info(\`main thread terminate, code:${code}\`);
  }
  _// Destroy Worker object_
  workerInstance.terminate();

}
_// After calling terminate, execute onexit_
workerInstance.onexit = (code) => {
  console.info(\`main thread terminate, code:${code}\`);
}

workerInstance.onerror = (err: ErrorEvent) => {
  console.error('main error message ' + err.message);
}

_// Work.ets & Worker.ets_
import { ErrorEvent, MessageEvents, worker } from '@kit.ArkTS';

_// Create an object in the worker thread that communicates with the main thread_
const workerPort = worker.workerPort;

_// The worker thread receives information from the main thread_
workerPort.onmessage = (e: MessageEvents): void => {
 _ // Data: Information sent by the main thread_
  let data: string = e.data;
  console.info(\`Work.ets onmessage: data ${data}\`);

 _ // Worker thread sends information to main thread_
  workerPort.postMessage('123');
}

_// Callback for worker thread error_
workerPort.onerror = (err: ErrorEvent) => {
  console.info('Worker.ets onerror' + err.message);
}

"buildOption": {
  "sourceOption": {
    "workers": \[
      "./src/main/ets/pages/Worker.ets",
      "./src/main/ets/pages/Work.ets"
    \]
  }
},

**参考链接**

[@ohos.worker (启动一个Worker)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-worker)