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