Java Thread – Executor framework, Timer and TimerTask

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , with 4 Comments on Java Thread – Executor framework, Timer and TimerTask

Tutorial and example of Executor framework, Timer and TimerTask over Thread

With the Thread class you could create your own timer class using the Thread.sleep(T) method to delay action for some time . This approach, however, has some drawbacks. For periodic events, if the processing times in between the sleep periods vary significantly, then the overall timing will mismatch. Also, if you need many timer events, the program will require many threads and use up system resources.

We can create a Timer functionality withExecutor frameworks and also there is Timer and Timertask available in java.util package. We will see both methods to create Timer functionality.

Method 1 : Using Executor framework

package com.G2.Thread;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class MyTimer1 implements Runnable {

	@Override
	public void run() {
		System.out.println("This is run method");

	}

}

public class TimerTask1Demo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MyTimer1 runnable = new MyTimer1();

		ScheduledExecutorService thread = Executors.newSingleThreadScheduledExecutor();

		/**
		 * Parameters :
		 * 1. Object of Runnable
		 * 2. Initial Delay
		 * 3. Delay between successive execution
		 * 4. Time Unit
		 */
		thread.scheduleAtFixedRate(runnable, 1000,1000, TimeUnit.MILLISECONDS);

	}
}

After every 1 sec the o/p will be printed.
To read more on ScheduledExecutorService refer below URL: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html

Method 2: Using java.util package for Progress bar animation in Swing

package com.G2.Thread;

import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class TimerTaskDemo2 {
	java.util.Timer fTimer;
	JProgressBar prg;

	class MyTimerTask extends TimerTask {
		public int progressValue = 0;

		@Override
		public void run() {
			progressValue++;
			prg.setValue(progressValue);
			if (progressValue > 100)
				fTimer.cancel();
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TimerTaskDemo2 obj = new TimerTaskDemo2();
		obj.createUI();

	}

	private void createUI() {
		JFrame f = new JFrame("Timer Task Demo");
		f.setLayout(null);
		prg = new JProgressBar();
		prg.setSize(200, 20);

		// Display percentage Text
		prg.setStringPainted(true);
		f.add(prg);

		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setSize(200, 100);
		f.setVisible(true);

		fTimer = new Timer();
		fTimer.schedule(new MyTimerTask(), 100, 100);
	}
}

Output:

Animation of ProgressBar in Swing Using TimerTask
Animation of ProgressBar in Swing Using TimerTask

In this example we have created a class “MyTimerTask”, which extends “TimerTask” and then created object of “Timer” by passing the “MyTimerTask” and scheduled to run after every 100 msec.

Related posts