这几天因为需要测试mongodb读写分离的问题,因此写了个定时查询程序,并且用到了多线程,以达到定时启动多个线程查询数据库的效果,下边代码记录备忘:
package timmer;
import java.util.Timer;
import java.util.TimerTask;
import mongoService.mongoServiceImp.AlarmServiceImpl;
import com.mongodb.DBObject;
public class StartTim {
// 从这里开始测试定时查询
public static void main(String[] args) {
Timer timer1 = new Timer();
// 在1秒后执行此任务,每次间隔5秒执行一次,
timer1.schedule(new MyTask(), 1000, 5000);
}
// java定时器要继承timerTask类
static class MyTask extends TimerTask {
AlarmServiceImpl alarmService = new AlarmServiceImpl();
// 调用定时器需要处理的业务
public void run() {
for (int i = 0; i < 3; i++) {
new Thread(new MyThread(alarmService)).start();
}
}
}
static class MyThread implements Runnable {
AlarmServiceImpl alarmService;
public MyThread(AlarmServiceImpl alarmService) {
super();
this.alarmService =