Synchronize java threads with timer and timerTask

java.util.timer  is a class that can be used to schedule (java  scheduler) tasks associated with a thread for execution in the future. Tasks can run once or repeatedly at regular intervals.

Multiple threads can share a single instance of timer provided there will be a synchronization of java.

java.util.TimerTask is an abstract class that implements the Runnable. We need to inherit from this class to create our TimerTask which will be scheduled using the timer. The timer uses the methods wait and notify to schedule processes.

Here is an example of the implementation of timer:

import java.awt.Toolkit; 
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTask{

static Toolkit toolkit;

public TimerTask(){
toolkit = Toolkit.getDefaultToolkit();
TimerTask timerTask = new executetask();
//run the timertask as a deamon
Timer timer = new Timer(true);
//shedule the task for future execution in a predefined time
timer.schedule(timerTask, 0, 1*1000);
System.out.println("TimerTask destarted");
//cancel after 10s
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
System.out.println("TimerTask stopped");
}

class executetask extends TimerTask {
@Override
public void run() {
System.out.println("Starts: "+new Date());
try {
//2 seconds to complete the task
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
toolkit.beep();
System.out.println("Finishes: "+new Date());
}
}

public static void main(String args[]){
new TimerTask();
}
}
Output

shedule tasks timer java

This is a simple example of a task manager. Timer will launch a  Task  every 1 second (1000 milliseconds) repetitively and a fixed interval. with the method schedule() which takes as arguments:
  • La  Task  to be ordered.
  • The Time Before the Task  would be executed. in milliseconds.
  • The time between successive executions of Tasks  or the execution frequency in milliseconds.
The results of compiling this program show that timer is waiting for the running process to finish so that it can move on to the next one in the queue.

The Timer.cancel() cancels the timer and all Tasks  in the queue. Once it's done, it's daemon thread is also terminated.

References:
Oracle: Timer class
Oracle:  timerTask class
java2s:Toolkit beep
javapoint: daemon thread