1. 程式人生 > >java.util.concurrent包(2)-執行緒池

java.util.concurrent包(2)-執行緒池

一、概述
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);
}
}