How to interrupt an Infinite Loop

前端 未结 12 1887
自闭症患者
自闭症患者 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条回答
  •  猫巷女王i
    2021-02-02 10:47

    We can achieve it using volatile variable, which we will change ouside Thread and stop the loop.

       for(;!cancelled;) /*or while(!cancelled)*/{
           System.out.println("Stackoverflow");
       }
    

    This is better way to write Infinite Loop.

    public class LoopInfinite{
          private static volatile boolean cancelled=false;
          public static void main(String[] args){
                 for(;!cancelled;) { //or while(!cancelled)
                        System.out.println("Stackoverflow");
                 }
          }
          public void cancel(){
            cancelled=true;
          }
    }
    

提交回复
热议问题