Java定时器

java循环执行任务

Timer 抛出异常缺陷,如果 TimerTask 抛出 RuntimeException,Timer 会终止所有任务的运行

Timer 管理时间延迟缺陷,Timer 在执行定时任务时只会创建一个线程任务,如果存在多个线程,若其中某个线程因为某种原因而导致线程任务执行时间过长,超过了两个任务的间隔时间

用 ScheduledExecutorService 替代 Timer

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

public class ScheduledExecutorTest {
	private ScheduledExecutorService scheatExec;

	ScheduledExecutorTest() {
		this.scheatExec = Executors.newScheduledThreadPool(8);
	}

	public Runnable makeTask(int number) {
		//创建任务
		//由于scheduleAtFixedRate 第一个参数必须是Runnable 类型
		return new Runnable() {
			public void run() {
				try {
					Thread.sleep(number);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("make task " + number);
			}
		};
	}

	public void addTask(Runnable RunnableTask) {
		this.scheatExec.scheduleAtFixedRate(RunnableTask, 0, 1000, TimeUnit.MILLISECONDS);
	}

	public static void main(String[] args) {
		ScheduledExecutorTest test = new ScheduledExecutorTest();
		Runnable task = test.makeTask(1000);
		Runnable task2 = test.makeTask(2000);
		test.addTask(task);
		test.addTask(task2);
	}
}
posted @ 2020-12-09 14:47  rm-rf*  阅读(112)  评论(0编辑  收藏  举报