如何在运行时打破无限循环?

时间:2015-05-13 01:40:09

标签: java eclipse

说我有:

b = true;
while(b){}

在此之后还有什么办法可以继续吗?像某种方法修改b的值而不停止并重新运行程序?

我想这样做是一种简单的方法,可以在不确定的时间内暂停程序,并且会一直在变化。

3 个答案:

答案 0 :(得分:2)

您可以从运行时可由用户修改的数据源中读取b的值。

这可以是来自数据库,网络套接字或简单文件的任何内容。

在这种情况下,我会推荐一个套接字。下面是一个非常粗略但有效的例子。

在Eclipse中启动程序后,需要打开一个终端窗口并telnet localhost 10008

通过套接字接受的命令是:

<numeric value> =暂停应用程序达到毫秒数

BYE =关闭套接字

STOP =完全停止应用

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class RuntimePause extends Thread {
    protected static boolean appRunning = true;
    protected Socket clientSocket;

    private long pause = 0;

    public static void main(String[] args) throws IOException {

        RuntimePause app = new RuntimePause();
        app.start();

        while (true) {
            app.listen();
        }

    }

    public void run() {

        while (appRunning) {

            System.out.println("App running...");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }

            if (pause > 0) {
                System.out.println("App pausing for " + pause + " ms");
                try {
                    Thread.sleep(pause);
                } catch (InterruptedException e) {
                }
                pause = 0;
            }

        }
    }

    public void listen() {

        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(10008);
            System.out.println("Connection Socket Created");
            try {
                while (appRunning) {
                    System.out.println("Waiting for Connection");
                    new NetworkSocket(serverSocket.accept());
                }
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port: 10008.");
            System.exit(1);
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Could not close port: 10008.");
                System.exit(1);
            }
        }
    }

    public class NetworkSocket extends Thread {

        public NetworkSocket(Socket clientSoc) {
            clientSocket = clientSoc;
            start();
        }

        public void run() {
            {
                System.out.println("New Communication Thread Started");

                try {
                    PrintWriter out = new PrintWriter(
                            clientSocket.getOutputStream(), true);
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream()));

                    String inputLine;

                    while ((inputLine = in.readLine()) != null) {
                        System.out.println("Received: " + inputLine);

                        // Client sent a pause command
                        try {
                            long pauseCommand = Long.parseLong(inputLine);
                            pause = pauseCommand;
                            out.println("OK, pausing for " + inputLine + " ms");
                        } catch (NumberFormatException e) {
                            //
                        }

                        // Client wishes to terminate connection to socket
                        if (inputLine.equals("BYE")) {
                            out.println("OK, bye!");
                            break;
                        }

                        // Client orders the app to stop
                        if (inputLine.equals("STOP")) {
                            out.println("OK, stopping!");
                            System.exit(1);
                        }
                    }

                    out.close();
                    in.close();
                    clientSocket.close();
                } catch (IOException e) {
                    System.err.println("Problem with Communication Server");
                    System.exit(1);
                }
            }
        }
    }
}

顺便说一下,这段代码还没有准备就绪。它只是作为如何解决问题的一个例子。您希望确保以线程安全的方式访问变量。

答案 1 :(得分:0)

BOOL b;

- (void)viewDidLoad {
    [super viewDidLoad];

    //Create a button
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    //Which is black
    button.backgroundColor = [UIColor blackColor];
    //Add it to the view
    [self.view addSubview:button];
    //When you press the button, do stopPrintingB method
    [button addTarget:self action:@selector(stopPrintingB) forControlEvents:UIControlEventTouchUpInside];


    b = true;
    /*
     * This is a GCD means not in the main thread
     * If you make while(b) in the main thread
     * the program will not do stopPrintingB method until the main thread is free
     */
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        while (b) {
            NSLog(@"printing b");
        }
    });
}

//make b false and stopPrintingB
- (void)stopPrintingB
{
    b = false;
}

答案 2 :(得分:0)

如果在调试模式下运行程序,则可以注入会破坏循环的代码。在发布的示例中只需更改:

@if(is_array($categories))
<ul>
    @foreach($categories as $key => $value)
    <li>
        @if(!is_numeric($key)) 
            <p>{{$key}}</p>
            @include('/admin/includes/category-menu-item', array('categories' => $value))
        @else
            <button data-category-id="{{$value->id}}">{{$value->name}}</button>
            @include('/admin/includes/category-menu-item', array('categories' => $value->children))
        @endif
    </li>
    @endforeach
</ul>
@endif

为:

b = true;
while(b){}

然后保存文件,循环将被破坏。