Threads 多线程
稳定性: 实验
Threads 模块提供了多线程支持,可以启动新线程来运行脚本。
脚本主线程会等待所有子线程执行完成后才停止执行,因此如果子线程中有死循环,请在必要的时候调用exit()
来直接停止脚本或threads.shutDownAll()
来停止所有子线程。
通过threads.start()
启动的所有线程会在脚本被强制停止时自动停止。
由于 JavaScript 自身没有多线程的支持,因此您可能会遇到意料之外的问题。
threads
threads.start(action)
action
{Function} 要在新线程执行的函数- 返回 Thread
启动一个新线程并执行 action。
例如:
threads.start(function () {
//在新线程执行的代码
while (true) {
log("子线程");
}
});
while (true) {
log("脚本主线程");
}
通过该函数返回的Thread对象可以获取该线程的状态,控制该线程的运行中。例如:
var thread = threads.start(function () {
while (true) {
log("子线程");
}
});
//停止线程执行
thread.interrupt();
更多信息参见Thread。
threads.shutDownAll()
停止所有通过threads.start()
启动的子线程。