How to interrupt an Infinite Loop

前端 未结 12 1886
自闭症患者
自闭症患者 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 11:02

    You can interrupt this thread by keeping its static reference of inherited reference to this Thread [main] by asking from Thread.currentThread(), like this

    public class LoopInfinite{
    public static Thread main = null;
    public static void main(String[] args){
        main = Thread.currentThread();
        for(;;)
           System.out.println("Stackoverflow");
        }
    }
    

    And to terminate you can call this from some other thread

    LoopInfinite.main.interrupt();
    

    But it will only work if both threads are part of the same group. Otherwise calling thread will get SecurityException

提交回复
热议问题