1.1 创建一个 thread,run() while 循环里 sleep();
(简单粗暴)
- public class Task1 {
- public static void main(String[] args) {
- // run in a second
- final long timeInterval = 1000;
- Runnable runnable = new Runnable() {
- public void run() {
- while (true) {
- System.out.println("Hello !!");
- // 试图使用线程休眠来实现周期执行,
- try {
- Thread.sleep(timeInterval);
- } catch(InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- };
- Thread thread = new Thread(runnable);
- thread.start();
- }
- }
1.2 使用 Timer 和 Timer Task
- 当启动和去取消任务时可以控制
- 第一次执行任务时可以指定你想要的 delay 时间
- import java.util.Timer;
- import java.util.TimerTask;
- public class HelperTest {
- public static void main(String[] args) {
- // TimerTask通过在run()方法里实现具体任务。
- TimerTask task = new TimerTask() {
- @Override
- public void run() {
- // task to run goes here
- System.out.println("Hello !!!");
- }
- };
- //Timer类可以调度任务。 Timer实例可以调度多任务,它是线程安全的。
- Timer timer = new Timer();
- long delay = 0;
- long intevalPeriod = 1 * 1000;
- // schedules the task to be run in an interval
- timer.scheduleAtFixedRate(task, delay, intevalPeriod);
- }
- }
1.3 ScheduledExecutorService
比较理想的定时任务实现方式
- 相比于 Timer 的单线程,它是通过线程池的方式来执行任务的
- 可以很灵活的去设定第一次执行任务 delay 时间
- 提供了良好的约定,以便设定执行的时间间隔
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
- public class Task3 {
- public static void main(String[] args) {
- Runnable runnable = new Runnable() {
- public void run() {
- // task to run goes here
- System.out.println("Hello !!");
- }
- };
- ScheduledExecutorService service = Executors.ScheduledThreadPoolExecutor(1);
- // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
- service.scheduleAtFixedRate(runnable, 200L, 200L, TimeUnit.MILLISECONDS);
- }
- }