Home > Enterprise >  How do you handle duplicate calls of Java threads?
How do you handle duplicate calls of Java threads?

Time:10-30

private int limitTime = 10;
void timer() {
    limitTime = 10;
    Thread thread = new Thread() {
        @Override
        public void run() { 
            stop = false;
            while(!stop) {
                System.out.println("Time >> "   limitTime);
                //Platform.runLater(()->{
                    lbLimitTime.setText(Integer.toString(limitTime));
                    limitTime -= 1;
                //});   
                    if(limitTime < 1) stop = true;
                try { Thread.sleep(1000); } catch (InterruptedException e) {}
            }
        };
    };
    thread.setDaemon(true);
    thread.start(); 
}

We are creating GUI programs using JavaFX.

I try to set a timer for 10 seconds every time I click.

If the timer function is duplicated by clicking 10 seconds before, the time goes twice as fast.

What part do you think I don't understand?

The timer function is called whenever a click occurs.

When a click occurs, I want to initialize the existing timer and flow normally for 1 second.

CodePudding user response:

Using Thread is not a good idea for your use case, use TimerTask and java.util.Timer

// class wide variables
TimerTask timerTask;
Timer timer = new Timer("myTimer");
int limitTimer = 10;

public TimerTask createTask() {
    limitTimer = 10;
    return new TimerTask() {
        @Override
        public void run() {
            System.out.println("Time>> "   limitTime);
            limitTime--;
            if (limitTime <= 0) {
                cancel();
            }
        }
    }
}

void click() {
   if (timerTask != null) {
      timerTask.cancel();
   }

   timerTask = createTask();
   timer.scheduleAtFixedRate(timerTask, 0, 1000);
}

When invoking click method, it'll cancel the old timer and starts a new one.

Note: limitTimer variable is not thread safe, so if you update it somewhere else, it can lead to strange behavior.

  • Related