/**
* JDK提供了ExecutorService实现了线程池功能:
* 线程池内部维护一组线程,可以高效执行大量小任务;
* Executors提供了静态方法创建不同类型的ExecutorService;
* 必须调用shutdown()关闭ExecutorService;
* ScheduledThreadPool可以定期调度多个任务。
*/
class TestThreadPool{ public static void main(String[] args) { Runnable task1 = new Runnable() { @Override public void run() { System.out.println("任务1"); } }; ExecutorService executor1 = Executors.newFixedThreadPool(5);//定长线程池 executor1.submit(task1); executor1.shutdown(); ExecutorService executor2 = Executors.newSingleThreadExecutor();//单线程池 executor2.submit(task1); executor2.shutdown(); ExecutorService executor3 = Executors.newCachedThreadPool();//单线程池 executor3.submit(task1); executor3.shutdown(); } }
//还有一种任务,需要定期反复执行,例如,每秒刷新证券价格。这种任务本身固定,需要反复执行的,可以使用ScheduledThreadPool。放入ScheduledThreadPool的任务可以定期反复执行。
ScheduledExecutorService ses = Executors.newScheduledThreadPool(5);
// 2秒后开始执行定时任务,每3秒执行一次:
ses.scheduleAtFixedRate(stask1, 2, 3, TimeUnit.SECONDS);
//创建指定动态范围的线程池
int corePoolSize = 5;//核心线程池大小
int maximumPoolSize = 10;//最大线程池大小
long keepAliveTime = 60L;//线程池中超过corePoolSize数目的空闲线程最大存活时间;可以allowCoreThreadTimeOut(true)使得核心线程有效时间
TimeUnit unit = TimeUnit.SECONDS;//keepAliveTime时间单位
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(10);//阻塞任务队列
ExecutorService es = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);//线程池的大小限制在5~10个之间动态调整
ExecutorService es0 = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());//动态创建
/**
* 1、构造一个固定线程数目的线程池,配置的corePoolSize与maximumPoolSize大小相同,同时使用了一个无界LinkedBlockingQueue存放阻塞任务,因此多余的任务将存在再阻塞队列,不会由RejectedExecutionHandler处理
*/
ExecutorService es1 = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
/**
* 2、构造一个缓冲功能的线程池,配置corePoolSize=0,maximumPoolSize=Integer.MAX_VALUE,keepAliveTime=60s,以及一个无容量的阻塞队列 SynchronousQueue,因此任务提交之后,将会创建新的线程执行;线程空闲超过60s将会销毁
*/
ExecutorService es2 = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
/**
* 3、构造一个只支持一个线程的线程池,配置corePoolSize=maximumPoolSize=1,无界阻塞队列LinkedBlockingQueue;保证任务由一个线程串行执行
*/
ExecutorService es3 = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
}