Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I break a loop in one Thread from another Thread?

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...

like image 319
Andrew Avatar asked Jan 27 '26 04:01

Andrew


1 Answers

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);
    }
}
like image 173
shmosel Avatar answered Jan 29 '26 18:01

shmosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!