How to break an infinite loop

寵の児 提交于 2019-12-11 05:54:07

问题


this is my piece of code:

// TODO Auto-generated method stub
        try
        {
            Socket clientSocket = new Socket("localhost", 8888);

            ObjectOutputStream ous = new ObjectOutputStream(clientSocket.getOutputStream());

            while(sending)
            {
                Statistics statsData = setStatisticsData();
                ous.writeObject(statsData);

                Thread.sleep(5000);
            }           
        }
        catch(UnknownHostException uhe) 
        {
            uhe.printStackTrace();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        } 
        catch (InterruptedException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

it's the client.it'll sending in an infinite loop an object Statistics. I would implement a way to break this infinite loop through input (es. press a button in the keyboard).ok can I do?how can i break an infinite loop?


回答1:


If this is a separate thread:

Thread statisticsSendingThread = ...

Then simply interrupt it:

statisticsSendingThread.interrupt();

InterruptedException will be thrown, escaping from the loop.

I see you already have a boolean sending flag. It will work as well, but with 5 second delay in worst case. Also make sure it is volatile - or better, use isInterrupted() method of thread. But interrupting the thread using interrupt() is by far the easiest way (no extra coding required). And your loop can be truly infinite (while(true) although with while(!isInterrupted())).


BTW your setStatisticsData() should probably be named getStatisticsData().




回答2:


You'll have to do them on separate threads, and since you are looking for user input it would probably be best to move your code to some asynchronous thread, then simply on input set your sending bool to false or interrupt the thread YourThread.interrupt();




回答3:


while(sending) 
{ 
    Statistics statsData = setStatisticsData(); 
    ous.writeObject(statsData); 
    Thread.sleep(5000);
    if(EXIT_FLAG == true)
       sending = false;
}    

EXIT_FLAG can be a static variable that can be updated from outside. You may also want to run this infinite loop in a separate Thread. Read more about how to share data between Threads.



来源:https://stackoverflow.com/questions/11433383/how-to-break-an-infinite-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!