Reputation: 87
I have a program that runs simultaneously and I have this problem where I want to stop the thread but the for loop/while loop doesn't get cancelled once I once I click enter
If I take the for
loop out of the while
loop, the program actually responds to the enter and shuts down.
class MyNumber extends Thread {
private volatile boolean processing = true;
public void run() {
while (processing) {
// Once I take this for loop out(put // beside it like right now), the enter key to stop the program then does work.
//for(int i = 1; i<27; i++){
System.out.println("Letter " + "i");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// }
}
}
public void permSleep() {
processing = false;
}
}
public class LetterNumber {
public static void main(String[] args) {
MyNumber num1 = new MyNumber();
num1.start();
System.out.println("Hit enter to stop the Numbers!");
Scanner shutter1 = new Scanner(System.in);
shutter1.nextLine();
num1.permSleep();
}
}
Why does the for
loop cause the program to not shutdown?
Upvotes: 5
Views: 167
Reputation: 31689
I'm not really clear on what you're asking. However, if you're expecting that the while
and for
loops will both terminate as soon as processing
is set to true
, that isn't what happens. A while
will execute the statement in the body (i.e. the for
loop), then it will test the condition (processing == true
), then if it's true, it executes the statement again, and then tests the condition again. It doesn't test it while the for
loop is executing. It doesn't "notice" when the processing
variable is set. So when processing
is set to true
, the for
loop will keep going until it's done, which could be another 26 seconds.
To fix this simply, add
if (!processing)
break;
inside the for
loop. Now the processing
flag will be tested each time through the for
loop. (If it were me, I'd put a "label" on the while
loop and use that to break
out of both loops.) Another way to fix it:
for(int i = 1; i<27 && processing; i++){
which means the for
loop will continue only as long as processing
is true
.
Note: These solutions will still not test processing
while the sleep(1000)
is going on. So the program could still pause up to 1 second before it terminates. If you really want a solution that will terminate the sleep
, you'll have use interrupt
or some other concurrency feature.
Upvotes: 2
Reputation: 41087
It should work. Your for
loop takes about 27
seconds to finish. It should come out of that after the for
loop has finished.
Upvotes: 1