0

I created a program that runs in a sort of loop, and it stops only if a particular event happens; i forgot to implement the possibility to interrupt the program from "outside", for example typing "halt" in the prompt.

So now i have something like this:

public void main(....) {
    instruction1;
    instruction2;

    while(true) {
        if(???) 
            break;
    }

}

And want change it in something like:

main() {
    do {
        instruction1;
        instruction2;
        ...
        ...
    } while(prompt do not contains 'halt');
Taylor Hx
  • 2,815
  • 23
  • 36
  • You will have to do this in two different threads.. take a look at this : http://stackoverflow.com/questions/8980240/getting-a-thread-to-pause-thread-wait-thread-notify . it has a nice expanded answer. – Zerkz Nov 28 '13 at 03:36
  • Additionally, if you want to just plainly stop the program in a command-line prompt environment (for most OSes,atleast), you can simply use Ctrl-C which in most cases will terminate the program (but not always...) – Zerkz Nov 28 '13 at 03:44

1 Answers1

0

I don't think that you want to turn main into a thread, try something like

while(true){
    if(inputScanner.hasNext() && inputScanner.next().equals("halt")){
        break;
    }
/* Do whatever is needed */
}

What happens is that the scanner is checked for input without blocking the loop with the hasNext() method, and then only when it does have data to read in does it read the data in.

flaviut
  • 2,007
  • 3
  • 23
  • 32
  • 1
    Both hasNext() and next() are able to block the thread. I don't think this is the correct approach. – Zerkz Nov 28 '13 at 03:38
  • You're right, but what I find surprising is that there is no way to check for input without blocking. – flaviut Nov 28 '13 at 03:45
  • Actually, further research shows that java.io.Reader has a ready() method that only returns true when read() would block. – flaviut Nov 28 '13 at 03:51
  • You are right on how ready() works. However, you won't be able to use it in this problem/context to achieve the solution. Chances are, ready() would always return false. See the answer @ http://stackoverflow.com/questions/5049319/how-to-create-a-java-non-blocking-inputstream-from-a-httpsurlconnection – Zerkz Nov 28 '13 at 04:11