Java多线程值之定时器Timer

时间:2022-08-08 00:11:05
package three.day.thread;

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

public class TraditionalThread {

public static void main(String[] args) {

new Timer().schedule(
new TimerTask(){
public void run() {
System.out.println(Thread.currentThread().getName());
}
}, 
10000,//该定时器10秒后开始启动
1000);//每隔1秒执行一次
}

}


以上在jdk1.5之前实现的方法,在jdk1.5后可以使用线程池实现,代码如下:

package three.day.thread;

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

public class TimerTest {

public static void main(String[] args) {
ScheduledExecutorService service =  Executors.newScheduledThreadPool(3);//
service.scheduleAtFixedRate(
new Runnable(){
public void run() {
System.out.println(Thread.currentThread().getName());
}

},
1,
1,
TimeUnit.SECONDS);

while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}


}