How to interrupt an Infinite Loop

前端 未结 12 1824
自闭症患者
自闭症患者 2021-02-02 10:36

Though I know it\'ll be a bit silly to ask, still I want to inquire more about the technical perspective of it.

A simple example of an infinite loop:

pub         


        
12条回答
  •  醉梦人生
    2021-02-02 10:51

    Add a variable shouldBreak or something which can be set using getter and setter.

    public class LoopInfinite {
    private boolean shouldBreak = false;
    
    public boolean isShouldBreak() {
        return shouldBreak;
    }
    
    public void setShouldBreak(boolean shouldBreak) {
        this.shouldBreak = shouldBreak;
    }
    
    public static void main(String[] args) {
        // Below code is just to simulate how it can be done from out side of
        // the class
        LoopInfinite infinite = new LoopInfinite();
        infinite.setShouldBreak(true);
        for (;;) {
            System.out.println("Stackoverflow");
            if (infinite.shouldBreak)
                break;
        }
    }
    

    }

提交回复
热议问题