如何实现循环机制,即函数调用自身直到不满足某些条件,或对函数调用进行排队

时间:2019-04-19 11:24:17

标签: java loops

我正在尝试将pythonintercept(使用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 here
root.after_idle(checkState)# calls function when no idle tasks
root.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();
}

请不要建议外部脚本,例如Sikuli和依赖平台的功能。我需要尽可能的“纯天然” Java。

-更新-

因为在WinXP上运行而使用JDK 1.8

1 个答案:

答案 0 :(得分:1)

由于@ cricket_007,使用ExecutorService可以轻松实现此循环机制。工作代码示例: 在构造函数中,我创建服务ExecutorService service = Executors.newCachedThreadPool();  在每个循环的结尾我都打电话给 service.submit(() -> loopname());