How to interrupt an Infinite Loop

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

提交回复
热议问题