How to interrupt an Infinite Loop

前端 未结 12 1975
自闭症患者
自闭症患者 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.

提交回复
热议问题