任务定时调度在多线程中有重要的地位和作用
通过Timer和Timetask,我们可以实现定时启动某个线程
java.util.Timer
在这种实现方式中,Timer类作用是类似闹钟的功能,也就是定时或者每隔一定时间触发一次线程。其实,Timer类本身实现的就是一个线程,只是这个线程是用来实现调用其它线程的。
constructor
Constructor Description Timer() Creates a new timer. Timer(boolean isDaemon) Creates a new timer whose associated thread may be specified to run as a daemon. Timer(String name) Creates a new timer whose associated thread has the specified name. Timer(String name, boolean isDaemon) Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.
Method
Method Modifier and Type Description void cancel() Terminates this timer, discarding any currently scheduled tasks. int purge() Removes all cancelled tasks from this timer’s task queue. void schedule (TimerTask task, long delay) Schedules the specified task for execution after the specified delay. void schedule(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. void schedule(TimerTask task, Date time) Schedules the specified task for execution at the specified time. void schedule(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. void scheduleAtFixedRate(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
java.util.TimerTask
TimerTask类是一个抽象类,该类实现了Runnable接口,所以该类具备多线程的能力。在这种实现方式中,通过继承TimerTask使该类获得多线程的能力,将需要多线程执行的代码书写在run方法内部,然后通过Timer类启动线程的执行。
constructor
Constructor Description protected TimerTask() Creates a new timer task.
Method
Method Modifier and Type Description boolean cancel() Cancels this timer task. abstract void run () The action to be performed by this timer task. long scheduledExecutionTime() Returns the scheduled execution time of the most recent actual execution of this task.
进行代码练习
package zy. thread. advancedTopics;
import java. util. Calendar;
import java. util. Date;
import java. util. GregorianCalendar;
import java. util. Timer;
import java. util. TimerTask;
public class TimerTest01 {
public static void main ( String[ ] args) {
Timer t = new Timer ( ) ;
t. schedule ( new myTask ( ) , 5000 ) ;
t. schedule ( new myTask ( ) , new Date ( 500 L) , 100 ) ;
t. schedule ( new myTask ( ) , 500 , 100 ) ;
Calendar cal = new GregorianCalendar ( 2020 , 10 , 5 , 1 , 12 , 54 ) ;
t. schedule ( new myTask ( ) , cal. getTime ( ) , 100 ) ;
}
}
class myTask extends TimerTask {
public void run ( ) {
for ( int i= 0 ; i< 6 ; ++ i)
System. out. println ( "----------冥想----------" ) ;
System. out. println ( "_____end_____" ) ;
}
}