一、概述
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任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-5任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-5任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-5任务正在运行
②不限制大小的线程池newCachedThreadPool
public class
CachedThreadPool
{
public static void main(String[] args)
{
//
不限制线程池的大小
// 当以前创建的线程可以使用时会重新使用
ExecutorService threadPool =
Executors.newCachedThreadPool();
for (int i = 0; i < 20;
i++)
{
threadPool.execute(new
MyTask());
}
threadPool.shutdown();
}
}
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-6任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-4任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-5任务正在运行
pool-1-thread-7任务正在运行
pool-1-thread-3任务正在运行
pool-1-thread-2任务正在运行
pool-1-thread-8任务正在运行
pool-1-thread-6任务正在运行
③单线程池newSingleThreadExecutor
public class
SingleThreadPool
{
public static void main(String[] args)
{
//
单线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for
(int i = 0; i < 20; i++)
{
threadPool.execute(new
MyTask());
}
threadPool.shutdown();
}
}pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
pool-1-thread-1任务正在运行
④定时任务线程池newScheduledThreadPool
public class
ScheduledPool
{
public static void main(String[] args)
{
//
定时任务线程池
ScheduledExecutorService threadPool =
Executors.newScheduledThreadPool(3);
// 三秒后运行任务
threadPool.schedule(new
MyTask(), 3, TimeUnit.SECONDS);
//
五秒钟后运行,每隔两秒钟执行一次
threadPool.scheduleAtFixedRate(new MyTask(), 5, 2,
TimeUnit.SECONDS);
}
}