为了账号安全,请及时绑定邮箱和手机立即绑定

如何实现循环机制,函数调用self直到某些条件不满足,或者排队函数调用

如何实现循环机制,函数调用self直到某些条件不满足,或者排队函数调用

喵喔喔 2022-10-12 16:07:03
我正在尝试将应用程序从 python(使用 TKinter)翻译成 Java。Tkinter 有一个循环机制,例如:<!-- language: python -->def checkState():    if checkCond1():        root.after_idle(cond1Loop)    elif checkCond2():        root.after_idle(cond2Loop)    elif checkCond3():        root.after_idle(cond3Loop)    else:        print('not found known state...')        root.update_idletasks() # waits for idle Tk tasks        root.after_idle(checkState)def cond1Loop():    # some checks here, may be looping deeper    root.after_idle(cond1Loop)def cond2Loop():    # some checks here, may be looping deeper    root.after_idle(cond2Loop)def cond3Loop():    # some checks here, may be looping deeper    root.after_idle(cond3Loop)root = Tk()mainWindow = Frame(root)# some win init hereroot.after_idle(checkState)# calls function when no idle tasksroot.mainloop()我的第一次尝试是使用定时器来实现它,但不能从它自己的函数中停止定时器:<!-- language: java-->private void mainLogicLoop(){    javax.swing.Timer localtimer = new javax.swing.Timer(100, e -> {        //finding state        if(checkCond1()){            System.out.println("I am at cond 1.");            cond1Loop();            //here i need to stop this timer,            //but localtimer is invisible from here.            //cond1Loop() will run its own timer...        }else        if(checkCond2()){            System.out.println("I am at cond 2.");            cond2Loop();            //here i need to stop this timer,            //but localtimer is invisible from here.            //cond2Loop() will run its own timer...        }else        if(checkCond3()){            System.out.println("I am at cond 3.");            cond3Loop();            //here i need to stop this timer,            //but localtimer is invisible from here.            //cond3Loop() will run its own timer...        }else{            System.out.println("No known conditions found.");        }    localtimer.start();}public static void main(String[] args) {    mainLogicLoop();}
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

这个循环机制很容易使用 ExecutorService 实现。工作代码示例:在构造函数中我创建服务ExecutorService service = Executors.newCachedThreadPool(); 并在每个循环结束时调用 service.submit(() -> loopname());



查看完整回答
反对 回复 2022-10-12
  • 1 回答
  • 0 关注
  • 115 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号