我如何打破一个无限循环,就像这个:
while(true){
if(???){
break;
}
}
Whitout 每次循环并要求输入时都会中断它?循环必须连续循环,直到用户打破它。
编辑
我想用一个键输入来打破它。
我如何打破一个无限循环,就像这个:
while(true){
if(???){
break;
}
}
Whitout 每次循环并要求输入时都会中断它?循环必须连续循环,直到用户打破它。
编辑
我想用一个键输入来打破它。
You could put the cycle in a separate thread.
import java.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
Thread t = new Thread(new Runnable() {
public void run() {
int cnt = 0;
while (true) {
System.out.println(cnt);
++cnt;
}
}
});
t.start();
System.in.read();
t.stop();
}
}
Let's analyze it line by line; first the imports:
import java.*;
import java.io.*;
class Main {
Then we need to declare that main throws IOException, because we'll be dealing with IO calls; a better option is obviously to correctly handle exceptions, but this is just a simple test.
public static void main(String[] args) throws IOException {
Then we create a thread which executes an infinite cycle; we will not be doing IO calls from this thread. The thread is not started until we call Thread.start(), and will run until we call Thread.stop().
Thread t = new Thread(new Runnable() {
public void run() {
int cnt = 0;
while (true) {
System.out.println(cnt);
++cnt;
}
}
});
Now we start the thread; the lines after this call will keep executing concurrently with the thread, so we will be able to wait for user input and stop the thread.
t.start();
System.in.read();
t.stop();
}
}
I think your best option is to use a flag controlled by another thread. You could do something like this:
private volatile boolean keepRunning = true;
public synchronized void stopRunning() {
keepRunning = false;
}
public void someProcess() {
new Thread() {
public void run() {
try (Scanner scanner = new Scanner(System.in)) {
keepWaiting = true;
while(keepWaiting) {
String userInput = scanner.next();
if("s".equals(userInput)) {
stopRunning();
keepWaiting = false;
}
}
}
}
}.start();
while(keepRunning){
doWork();
}
}
The loop should keep running until the user enters "s". Of course it's a very basic implementation but you get the idea.
Also, you don't really need the "stopRunning()" method, the thread could access the flag directly, but you would need it if you wanted to run the thread from somewhere else.
最好使用这个。
boolean doLoop = true;
while(doLoop){
if(userTerminates()){ //user terminates it?
doLoop = false;
}
}
private boolean userTerminates(){
Scanner scanner = new Scanner(System.in);
//If you want that user terminates it with 'c' char
return scanner.nextLine().equals("c");
}