一:简单线程实现
package test.cxf.Timer;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 很简单也很傻的定时器,就是用线程休眠实现
* @author feifei
* @Date 2021/8/20 18:57:28
* @Version 1.0
*/
public class ThreadTest {
private static SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final long PERIOD=2000;
private static final long DEALY=1000;
public static void main(String[] args) {
int count=0;
while(true){
if(count==0){
try {
Thread.sleep(DEALY);
count=1;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("定时器:"+format.format(new Date()));
try {
Thread.sleep(PERIOD);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
timer计时器
package test.cxf.Timer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* 基于timer实现的定时器,本质上还是单线程进行的,一个定时器会对另一个定时器产生影响
* @author feifei
* @Date 2021/8/20 18:36:58
* @Version 1.0
*/
public class TimerTest {
private static SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static void main(String[] args) {
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Timer的第一个定时器:"+format.format(new Date()));
}
},0,2000);
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Timer的第二个定时器:"+format.format(new Date()));
}
},0,2000);
}
}
可以看出定时器一本来设定的循环事件是2秒,由于timer本质上还是单线程实现的,计时器二的睡眠会对定时器一造成影响
ScheduledThreadPool的计时器
package test.cxf.Timer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 基于线程池试下的定时器,同时也是这三种中最好的
* @author feifei
* @Date 2021/8/20 18:46:57
* @Version 1.0
*/
public class ExecutorsTest {
private static SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(3);
public static void main(String[] args) {
scheduledExecutor.scheduleWithFixedDelay(new TimerTask() {
@Override
public void run() {
System.out.println("第一个定时器:"+format.format(new Date()));
}
},0,2, TimeUnit.SECONDS);
scheduledExecutor.scheduleWithFixedDelay(new TimerTask() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二个定时器:"+format.format(new Date()));
}
},0,2, TimeUnit.SECONDS);
}
}
基于线程池实现的定时器,可靠性也是最好的