簡體   English   中英

如何在運行時中斷無限循環?

[英]How can I break an infinite loop at runtime?

說我有:

b = true;
while(b){}

在此之后有什么繼續的方法嗎? 喜歡某種無需停止並重新運行程序即可修改b值的方法嗎?

我想將其作為一種簡單的方法來暫停程序一段未指定的時間,該時間一直在變化。

您可以從用戶在運行時可修改的數據源中讀取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);
                }
            }
        }
    }
}

順便說一句,此代碼尚未准備就緒。 它只是作為如何解決問題的示例。 您要確保以線程安全的方式訪問變量。

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;
}

如果以調試模式運行程序,則可以注入將破壞循環的代碼。 在發布的示例中,只需更改:

b = true;
while(b){}

至:

b = true;
while(b){b=false;}

然后保存文件,循環將中斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM