A simple Timer example
Shan Ge http://9cbs.blog.net/duoshan
Sometimes you want to change a certain interval to perform a duplicate task, Java.util.Timer can help you very simple. Of course, you can also be implemented in multithreading. Here is to implement this feature with java.util.timer.
//mytask.java defines the Timertask task, we will call in Dotask.
/ / This is just a simple printing task parameter
Public class mytask extends java.util.timertask {string jobname; private int i; public void run () {// run in interface runnable system.out.println (jobname);
Public mytask (string jobname) {this.jobName = jobName;}}
//dotask.java
Import java.util. *; import java.io. *;
Public class dotask {private java.util.timer timer; private java.util.timertask task; public dotask (java.util.timertask task) {this.timer = new time (); this.task = task;} public void Start (int ", int interface) {Timer.Schedule (task, delay * 1000, internal * 1000); // utilize Timer.Schedule method}
Public static void main (string [] args) {java.util.timertask task1 = new mytask ("job 1"); java.util.timertask task2 = new mytask ("job 2"); dotask pt = new dotask (Task1 ); Pt.start (1, 3); dotask pt2 = new dotask (task2); pt2.start (1, 1);
}
The result is as follows; the output of each thread is alternated with each other
Job 1JOB 2JOB 2JOB 2 Job 1Job 2Job 2Job 2 ..