I am new to Java and I am trying to use one Thread to finish a loop in another Thread regardless of the state of the loop.
public static void main(String[] args) {
// Either start the other thread here
while(true){
// Or here, not quite sure
// Do stuff
}
}
}
public class Timer implements Runnable{
@Override
public void run() {
long start = System.currentTimeMillis();
while(true) {
long current = System.currentTimeMillis();
if(current - start == 10000){
// How do I notify the loop in main to break?
break;
}
}
}
}
What I am trying to do is end the loop in main after 10 seconds, regardless of the state of its loop because the loop contains a Scanner reading from System.in, and it needs to stop after 10 seconds regardless of what has been read from the keyboard or not. I thought the best solution would be to have a timer Thread running which counts the seconds, and then notify the loop in the other Thread somehow, after 10 seconds, to break, however, I do not know how to implement this...
If your goal is to stop looping after 10 seconds, there's no reason to use another thread. Just check the time locally:
public class Main {
public static void main(String[] args) {
// Instructions
long start = System.currentTimeMillis();
do {
//Instructions
//Instructions
//...
//Instructions
} while (System.currentTimeMillis() - start < 10000);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With