五、定时任务线程池
图例:

代码演示:
其中定义线程池和执行线程的主类:ScheduleThreadPoolTest,和线程实现类:Task
package com.tuling.pool;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleThreadPoolTest {
    public static void main(String[] args) {
        //定义一个线程池来执行线程,就避免了Timer的弊端
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        for (int i=0;i<2;i++){  //开两个线程任务
            //调用schedule()方法,传参里有(线程任务,延迟时间,时间单位)
            //调用scheduleAtFixedRate()方法,传参里有(线程任务,延迟时间,间隔时间,时间单位)
            scheduledThreadPool.scheduleAtFixedRate(new Task("task-"+i),0,2, TimeUnit.SECONDS);
        }
    }
}
class Task implements Runnable{
    private String name;
    public Task(String name) {
        this.name = name;
    }
    public void run() {
        try {
            System.out.println("name="+name+",startTime="+new Date());
            Thread.sleep(3000);
            System.out.println("name="+name+",endTime="+new Date());
            //线程池执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
- 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 - 11
 - 12
 - 13
 - 14
 - 15
 - 16
 - 17
 - 18
 - 19
 - 20
 - 21
 - 22
 - 23
 - 24
 - 25
 - 26
 - 27
 - 28
 - 29
 - 30
 - 31
 - 32
 - 33
 - 34
 - 35
 - 36
 - 37
 - 38
 - 39
 - 40
 
问题补充图:Leader-Follower模式

