Question

I have implemented a down counter in java in a separate class that has a starting time in seconds to start down counting to zero but when it does reach the zero I need it to make some thread in other file to stop do their jobs how could I do that?

here is my counter code:

public class Stopwatch {
    static int interval;
    static Timer timer;

    public void start(int time) {
        Scanner sc = new Scanner(System.in);
        int delay = 1000;
        int period = 1000;
        timer = new Timer();
        interval =time; 
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
               // System.out.println(setInterval());
                setInterval();
            }
        }, delay, period);
    }

    public int time() {
        return interval;
    }

    private static final int setInterval() {
        if (interval == 1)
            timer.cancel();
        return --interval;
    }
}

thanks in advance.

Was it helpful?

Solution

Depending on what the other thread is doing, I'd suggest interrupts or having a boolean value set (and checked in the other thread). If execution of the other thread can be stopped at any time use an interrupt, however if execution cannot be stopped after a certain point in time, simply set/check a boolean before that code is entered.

Add a boolean to your stopwatch class:

private static boolean continue = true;

Create a method to check the boolean:

public static boolean shouldContinue() {
    return this.continue;
}

Modify your setInterval() to change the boolean:

private static final int setInterval() {
    if (interval == 1)
        continue = false;
    return --interval;
}

Add the check somewhere in your other class:

if (!(Stopwatch.shouldContinue())) {
    return;
}

or

if (Stopwatch.shouldContinue()) {
    //do work here
}

Since it sounds like my comments helped, I thought I'd make it into an answer so we can remove this from the unanswered list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top