阻塞线程的意义:所有线程执行完毕才返回。
传统线程:所有任务分发完毕即返回。
见代码:
package com.test.test;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/** * 阻塞模式线程池 * * @author WebSOS * @blog http://54sb.org * */public class TaskPool { ExecutorService exePool; private Listrunnables = new ArrayList (); private boolean isActivity = true; private Integer maxThread=100; private Integer timeOutSeconds=60; public Integer getMaxThread() { return maxThread; } public void setMaxThread(Integer maxThread) { this.maxThread = maxThread; } public TaskPool() { } public TaskPool(Integer maxThread,Integer timeOutSeconds) { this.maxThread=maxThread; this.timeOutSeconds=timeOutSeconds; } public TaskPool(List runnables) { this.runnables.addAll(runnables); } public void execute(List runnables) { pushTask(runnables); execute(); } public void execute() { if (!isActivity) { System.out.println("RobotTaskPool:线程池已销毁=================="); } isActivity = false; if (runnables==null||runnables.isEmpty()) { return; } Integer currThread = runnables.size(); if (currThread > maxThread) { currThread = maxThread; } exePool = Executors.newFixedThreadPool(maxThread); System.out.println("RobotTaskPool:[" + maxThread + "]执行中=================="); for (Runnable runnable : runnables) { exePool.execute(runnable); } exePool.shutdown(); try { exePool.awaitTermination(timeOutSeconds, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("RobotTaskPool:[" + maxThread + "]执行完毕=================="); } public boolean pushTask(List runnables) { if (!isActivity) { System.out.println("RobotTaskPool:线程池已销毁=================="); } this.runnables.addAll(runnables); return isActivity; } public boolean pushTask(Runnable runnable) { if (!isActivity) { System.out.println("RobotTaskPool:线程池已销毁=================="); } runnables.add(runnable); return isActivity; } public static void main(String[] args) { }}