Understanding the Timer Class Schedule Method for Java

Asked 2 years ago, Updated 2 years ago, 33 views

I wanted to implement the timeout using the Timer class schedule method.

to.schedule(time,1000);

After 1000 ms, the time object is processed as shown in .

class TimeOut extensions TimerTask {
    private boolean isStop=false;
    public void run() {
        isStop = true;
    }
    public boolean getStop(){
        return isStop;
    }
}

On the other hand, the execution of this time object is defined by the run() method in the TimeOut class that inherited the TimerTask.
This is only true in the isStop variable, and later

 if(time.getStop()==true){
      /* Processing*/
}

I would like to use the isStop variable to determine if it has timed out.
However, if the time object runs() after 1000 ms, it seems that the contents of the object have been discarded and isStop cannot be viewed later.
What should I do in this case?

java

2022-09-30 16:24

1 Answers

Is the run method called for the TimeOut class?
If you use Timer, you would normally call the action as follows:

finalTimeOut timeOut=newTimeOut();
final Timer timer = new Timer();

System.out.println(timeOut.getStop());

timer.schedule(timeOut, 1000);
// wait ten seconds for processing
TimeUnit.SECONDS.sleep(10);
timer.cancel();

System.out.println(timeOut.getStop());

If you invoke the cancel method in the Timer class without waiting for processing after 1000 ms, the run method in the TimeOut class is not invoked.

By the way, the first output is false and the last output is true.


2022-09-30 16:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.