回答
有停止线程的代码。threads.start() 启动线程后会返回一个 Thread 对象,你可以通过该对象或 threads 模块提供的方法来停止线程。
主要有以下三种停止方式:
-
停止单个线程
使用thread.interrupt()方法停止特定的线程。 -
停止所有子线程
使用threads.shutDownAll()方法停止所有通过threads.start()启动的子线程。 -
停止整个脚本
使用exit()方法直接停止脚本运行,所有子线程也会随之自动停止。
注意事项:
脚本主线程会等待所有子线程执行完成后才停止执行。如果子线程中存在死循环,必须在必要时调用停止方法,否则脚本无法正常结束。
代码示例:
// 文档地址 https://docs.hamibot.com/
// 启动一个子线程
var thread = threads.start(function () {
while (true) {
log('子线程运行中');
sleep(1000);
}
});
// 主线程等待 5 秒
sleep(5000);
// 停止该子线程
thread.interrupt();
log('单个线程已停止');
// 或者使用 threads.shutDownAll() 停止所有子线程
// threads.shutDownAll();
如果涉及多个线程协作或需要更复杂的控制,建议结合 threads.lock() 或 threads.atomic() 确保线程安全。
ℹ️ 本回答由 AI 生成,内容仅供参考