java.util.concurrent.executors 提供了 java.util.concurrent.executor 接口的一个Java实现,可以创建线程池。下面是一个简单示例:
package threadPool; /** * Function: <br/> * Date: 2014-1-14 上午1:45:41 <br/> * * @author june: decli#qq.com */ public class WorkerThread implements Runnable { private String command; public WorkerThread(String s) { this.command = s; } public void run() { System.out.println(Thread.currentThread().getName() + " Start. Command = " + command); processCommand(); System.out.println(Thread.currentThread().getName() + " End."); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString() { return this.command; } }下面是一个测试程序,从 Executors 框架中创建固定大小的线程池:
package threadPool; /** * Function: <br/> * Date: 2014-1-14 上午1:58:03 <br/> * @author june: decli#qq.com */ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SimpleThreadPool { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread("" + i); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads"); } }在上面的程序中,我们创建了包含5个工作线程的固定大小线程池。然后,我们向线程池提交10个任务。由于线程池的大小是5,因此首先会启动5个工作线程,其他任务将进行等待。一旦有任务结束,工作线程会从等待队列中挑选下一个任务并开始执行。
pool-1-thread-2 Start. Command = 1 pool-1-thread-4 Start. Command = 3 pool-1-thread-1 Start. Command = 0 pool-1-thread-3 Start. Command = 2 pool-1-thread-5 Start. Command = 4 pool-1-thread-4 End. pool-1-thread-5 End. pool-1-thread-1 End. pool-1-thread-3 End. pool-1-thread-3 Start. Command = 8 pool-1-thread-2 End. pool-1-thread-2 Start. Command = 9 pool-1-thread-1 Start. Command = 7 pool-1-thread-5 Start. Command = 6 pool-1-thread-4 Start. Command = 5 pool-1-thread-2 End. pool-1-thread-4 End. pool-1-thread-3 End. pool-1-thread-5 End. pool-1-thread-1 End. Finished all threads
package threadPool; /** * Function: <br/> * Date: 2014-1-14 上午2:19:23 <br/> * @author june: decli#qq.com */ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.println(r.toString() + " is rejected"); } }ThreadPoolExecutor 提供了一些方法,可以查看执行状态、线程池大小、活动线程数和任务数。所以,我通过一个监视线程在固定间隔输出执行信息。
package threadPool; /** * Function: <br/> * Date: 2014-1-14 上午2:19:52 <br/> * @author june: decli#qq.com */ import java.util.concurrent.ThreadPoolExecutor; public class MyMonitorThread implements Runnable { private ThreadPoolExecutor executor; private int seconds; private boolean run = true; public MyMonitorThread(ThreadPoolExecutor executor, int delay) { this.executor = executor; this.seconds = delay; } public void shutdown() { this.run = false; } public void run() { while (run) { System.out .println(String .format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s", this.executor.getPoolSize(), this.executor.getCorePoolSize(), this.executor.getActiveCount(), this.executor.getCompletedTaskCount(), this.executor.getTaskCount(), this.executor.isShutdown(), this.executor.isTerminated())); try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }下面是使用 ThreadPoolExecutor 的线程池实现示例:
package threadPool; /** * Function: <br/> * Date: 2014-1-14 上午2:22:15 <br/> * @author june: decli#qq.com */ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class WorkerPool { public static void main(String args[]) throws InterruptedException { //RejectedExecutionHandler implementation RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl(); //Get the ThreadFactory implementation to use ThreadFactory threadFactory = Executors.defaultThreadFactory(); //creating the ThreadPoolExecutor ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory, rejectionHandler); //start the monitoring thread MyMonitorThread monitor = new MyMonitorThread(executorPool, 3); Thread monitorThread = new Thread(monitor); monitorThread.start(); //submit work to the thread pool for (int i = 0; i < 10; i++) { executorPool.execute(new WorkerThread("cmd" + i)); } Thread.sleep(30000); //shut down the pool executorPool.shutdown(); //shut down the monitor thread Thread.sleep(5000); monitor.shutdown(); } }
在初始化 ThreadPoolExecutor 时,初始线程池大小设为2、最大值设为4、工作队列大小设为2。所以,如果当前有4个任务正在运行而此时又有新任务提交,工作队列将只存储2个任务和其他任务将交由RejectedExecutionHandlerImpl 处理。
程序执行的结果如下,确认了上面的结论:
pool-1-thread-1 Start. Command = cmd0 pool-1-thread-2 Start. Command = cmd1 cmd6 is rejected cmd7 is rejected cmd8 is rejected cmd9 is rejected pool-1-thread-3 Start. Command = cmd4 pool-1-thread-4 Start. Command = cmd5 [monitor] [0/2] Active: 1, Completed: 0, Task: 4, isShutdown: false, isTerminated: false [monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false pool-1-thread-1 End. pool-1-thread-1 Start. Command = cmd2 pool-1-thread-2 End. pool-1-thread-2 Start. Command = cmd3 pool-1-thread-3 End. pool-1-thread-4 End. [monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false [monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false pool-1-thread-1 End. pool-1-thread-2 End. [monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true请注意活跃线程、已完成线程和任务完成总数的变化。我们可以调用 shutdown() 结束所有已提交任务并终止线程池。
如果希望延迟执行或定期运行任务,那么可以使用 ScheduledThreadPoolExecutor 类。要了解更多,请参见:
Java ScheduledThreadPoolExecutor Example to schedule tasks after delay and execute periodically
http://www.journaldev.com/2340/java-scheduledthreadpoolexecutor-example-to-schedule-tasks-after-delay-and-execute-periodically
Java Thread Pool Example using Executors and ThreadPoolExecutor
http://www.journaldev.com/1069/java-thread-pool-example-using-executors-and-threadpoolexecutor#comment-25902