UI模式下不能使用sleep


3.4 UI模式下不能使用sleep

写好逻辑代码,要优化一下加上界面,发现在界面模式下直接调用函数时,如果有sleep延时语句,运行时会报错导致程序无法运行,会出现以下提示



Error: 不能在ui线程执行阻塞操作,请使用setTimeout代替



然而,使用setTimeout确实也无法解决问题。
解决方案:
使用新的线程执行,部分代码块如下。其中threads.start(main)中的main,是自定义的function man()函数 


"ui";var threadMain=nullui.layout( <vertical padding="16"> <button id="myThreadStart" text="启动程序" w="*" style="Widget.AppCompat.Button.Colored" /> <button id="myThreadStop" text="终止程序并退出" w="auto"/> </vertical>);
ui.myThreadStart.on("click", () => { if(threadMain==null) { threadMain = threads.start(main); }else { toast("程序已在运行,请点击停止"); }});ui.myThreadStop.on("click", () => { if(threadMain==null) { toast("没有程序在运行"); exit(); }else { toast("程序线程已停止"); threadMain.interrupt(); threadMain = null; exit(); }});