一、概述
java.util.concurrent中有非常方便的线程池实现,提供的executor框架包含用于管理实现runnable任务,executors类提供了许多不同类型的executor实现的静态工厂方法。
二、实例
public class mytask implements runnable
{
public void run()
system.out.println(thread.currentthread().getname() + "任务正在运行");
}
①固定大小线程池newfixedthreadpool
public class fixedthreadpooltest
public static void main(string[] args)
// 创建固定大小为5的线程池
executorservice threadpool = executors.newfixedthreadpool(5);
// 模拟执行了20个任务,而线程池中只有5个线程
for (int i = 0; i < 20; i++)
try
// 一次执行五个任务,其余任务排队
thread.sleep(20);
threadpool.execute(new mytask());
catch (exception e)
e.printstacktrace();
threadpool.shutdown();
pool-1-thread-1任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-5任务正在运行
②不限制大小的线程池newcachedthreadpool
public class cachedthreadpool
// 不限制线程池的大小
// 当以前创建的线程可以使用时会重新使用
executorservice threadpool = executors.newcachedthreadpool();
pool-1-thread-6任务正在运行
pool-1-thread-7任务正在运行
pool-1-thread-8任务正在运行
③单线程池newsinglethreadexecutor
public class singlethreadpool
// 单线程池
executorservice threadpool = executors.newsinglethreadexecutor();
}pool-1-thread-1任务正在运行
④定时任务线程池newscheduledthreadpool
public class scheduledpool
// 定时任务线程池
scheduledexecutorservice threadpool = executors.newscheduledthreadpool(3);
// 三秒后运行任务
threadpool.schedule(new mytask(), 3, timeunit.seconds);
// 五秒钟后运行,每隔两秒钟执行一次
threadpool.scheduleatfixedrate(new mytask(), 5, 2, timeunit.seconds);