如何在Java中的任何行上中断一个循环?

问题描述 投票:0回答:1

我想基于某种外部输入(int,字符串或其他任何类型)立即终止循环,但是我不知道它何时到来,java中是否有某种异步方法可以在特定时刻执行操作?具体输入到来?

或多或少我想做的事的例子:


public void run(){
    while(/*condition*/){

        //let's say it receives a String more times like this:
        String s = inSocket.readLine();

        // and in the bottom, I could put an if:
        if(s.equals("stop")){
        break;
        }
    }

// here some other code that I still want to execute, exiting the cycle

}

在这种情况下,循环仅在我写break的特定行处停止;我希望它能够在接收到的字符串“停止”时立即中断,但是我不知道何时会出现,因为我在执行过程中收到了多个字符串。

java multithreading while-loop break
1个回答
0
投票

首先,关于您要创建的asynchronous任务,您没有提供太多信息。

© www.soinside.com 2019 - 2024. All rights reserved.