tnanoha
tnanoha

Reputation: 55

About java Timer

I am doing some testing with Timer in java.

My program starts a Timer, then waits for 2 seconds, cancels the Timer and prints out the j variable.

However the Timer still runs even though I canceled it. Thanks.

public static Timer time;
public static int j=0;

    public static void main(String[] args)
    {
        try {
            testrun();
            Thread.sleep(2000);
            time.cancel();
            System.out.println("timer stop");

            System.out.println(j);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void testrun()
    {
        time = new Timer();
        time.schedule(new TimerTask() {
              @Override
              public void run() {
                  for(int i = 0;i<100;i++){
                  System.out.println(i);
                  j++;
                  }

                  System.out.println("End timer");
              }
            }, 1000, 1000);
    }

Upvotes: 2

Views: 197

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65889

Because cancel only aborts the timer - if the task has begun it will run to completion.

If you wish to abort the task you need to keep track of it and call it's interrupt method.

public static Timer time = new Timer();
public static Thread runningThread = null;
public static int j = 0;

public static void main(String[] args) {
    try {
        testrun();
        Thread.sleep(2000);
        time.cancel();
        System.out.println("timer stop");
        if (runningThread != null) {
            // Interrupt the thread.
            runningThread.interrupt();
        }
        System.out.println(j);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void testrun() {
    time.schedule(new TimerTask() {
        @Override
        public void run() {
            // Catch the thread that is running my task.
            runningThread = Thread.currentThread();
            for (int i = 0; i < 100; i++) {
                System.out.println(i);
                j++;
            }

            System.out.println("End timer");
        }
    }, 1000, 1000);
}

Upvotes: 2

chiastic-security
chiastic-security

Reputation: 20520

The call to Timer.cancel() will stop any further scheduled but unexecuted tasks from being executed, but it won't interrupt a running task.

See the Javadoc for Timer.cancel() (emphasis mine):

Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists).

Upvotes: 1

Related Questions