实现多线程定时任务

场景:

后台服务启动时需要启动一个无限循环的定时任务

实现:

.....
public class Demo extends HttpServlet {
	public void init() throws ServletException {
		super.init();
		ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
		scheduler.scheduleWithFixedDelay(new Runner(), 0, 5, TimeUnit.SECONDS);
	}
	
	public class Runner implements Runnable {
		public void run() {
			......
		}
	}
	......
}

备注:与while(true) Thread.sleep方式相比,更容易控制并可轻易实现多线程

原文: http://www.54chen.com/java-ee/java-example-whiletrue-thread-sleep.html

你可能感兴趣的:(多线程,定时任务)