如何打破无限循环 [英] How to break an infinite loop

查看:43
本文介绍了如何打破无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的一段代码:

// 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?

推荐答案

如果这是一个单独的线程:

If this is a separate thread:

Thread statisticsSendingThread = ...

然后简单地打断它:

statisticsSendingThread.interrupt();

InterruptedException 将被抛出,逃离循环.

InterruptedException will be thrown, escaping from the loop.

我看到你已经有了一个布尔值 sending 标志.它也可以工作,但在最坏的情况下会延迟 5 秒.还要确保它是 volatile - 或者更好,使用线程的 isInterrupted() 方法.但是使用 interrupt() 中断线程是迄今为止最简单的方法(不需要额外的编码).并且您的循环可以是真正无限的(while(true) 尽管使用 while(!isInterrupted())).

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())).

顺便说一句,你的 setStatisticsData() 应该被命名为 getStatisticsData().

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

这篇关于如何打破无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆