How to interrupt an Infinite Loop

前端 未结 12 1844
自闭症患者
自闭症患者 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:55

    You can get at the thread running the infinite loop from a different thread and call interrupt on it. You'll have to be very sure what you are doing though, and hope that the interrupted thread will behave properly when interrupted.

    Here, I've named the thread with the offending loop for easier identification. Beware that the following solution is vulnerable to race conditions.

        Thread loop = new Thread() { 
    
            public void run() {
                Thread.currentThread().setName("loop");
                while(true) {
                    System.out.print(".");
                }
            }
        }.start();
    

    Then in some other class:

        ThreadGroup group = Thread.currentThread().getThreadGroup();
        Thread[] threads = new Thread[group.activeCount()];
        group.enumerate(threads);
    
        for(Thread t : threads) {
            if(t.getName().equals("loop")) {
                /* Thread.stop() is a horrible thing to use. 
                   Use Thread.interrupt() instead if you have 
                   any control over the running thread */
                t.stop();
            }
        }
    

    Note that in my example I assume the two threads are in the same ThreadGroup. There is no guarantee that this will be the case, so you might need to traverse more groups.

    If you have some control over this, a decent pattern here would be to have while(!isInterrupted()) instead in the loop declaration and use t.interrupt() instead of t.stop().

    My only advice to you, even after posting this, is to not do this. You can do it, but you really shouldn't.

    0 讨论(0)
  • 2021-02-02 10:56

    Your kind of problem looks like a Threading problem. But still, it is now a a good practice to include a stopping flag even in threads

    0 讨论(0)
  • 2021-02-02 10:58

    If you need an "infinite" loop, you sure need a thread (else your app will be stuck until the end of the loop).

    class BigLoop extends Thread
    {
    
        private boolean _sexyAndAlive = true;
    
        // make some constructor !
    
        public void softTerminate()
        {
        _sexyAndAlive = false;
        }
    
    
        public void run()
        {
            try
            {
                while( _sexyAndAlive )
                {
                   // Put your code here 
                }
            }
            catch( Some Exceptions ... )
            {
                // ...
            }
            // put some ending code here if needed
        }
    }
    
    
    // in another file :
    
    BigLoop worker = new BigLoop();
    worker.start(); // starts the thread
    
    // when you want to stop it softly
    worker.softTerminate();
    

    So, this is a simple method to have background running loop.

    0 讨论(0)
  • 2021-02-02 10:59

    I think this is not possible. Only using break within the loop. You could use

    while(cond) {}
    

    And from some other place make it false

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-02 11:08

    Here is what I did:

    while(Exit == false){
        Scanner input = new Scanner(System.in);
        String in = input.next();
    
        switch(in){
            case "FindH": 
                FindHyp hyp = new FindHyp();
                float output = hyp.findhyp();
                System.out.println(output); 
            case "Exit":
                Exit = true;
        break;
    
        }
      }  
    
    0 讨论(0)
提交回复
热议问题