使用JDK1.5中的Executors可以创建线程池实现并发操作,详细实现可查看JDK源码,以下是本人整合的工具类:
package xxx.task; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import com.comtop.cap.common.util.CollectionUtils; import com.comtop.cap.common.util.StringUtil; /** * 线程任务执行器 * * @author 许畅 * @since JDK1.7 * @version 2017年5月11日 许畅 新建 */ public final class ThreadTaskExecutor { /** 最大线程连接数 */ private static final int MAX_THREAD_CONNECTION = 15; /** * 构造方法 */ private ThreadTaskExecutor() { } /** * 执行线程任务 * * @param tasks 线程任务 * @return 结果集 */ public static List<TaskResult> invokeAll(List<Callable<TaskResult>> tasks) { List<TaskResult> results = new ArrayList<TaskResult>(); int nThreads = tasks.size() > MAX_THREAD_CONNECTION ? MAX_THREAD_CONNECTION : tasks.size(); ExecutorService service = Executors.newFixedThreadPool(nThreads); try { List<Future<TaskResult>> taskResults = service.invokeAll(tasks); for (Future<TaskResult> future : taskResults) { results.add(future.get()); } } catch (InterruptedException e) { results.add(new TaskResult("发生线程中断异常:" + e.getMessage())); } catch (ExecutionException e) { results.add(new TaskResult("发生线程执行异常:" + e.getMessage())); } finally { service.shutdown(); } return results; } /** * 执行单个线程任务 * * @param task 线程任务 * @return 执行结果集 */ public static TaskResult submit(Callable<TaskResult> task) { ExecutorService service = Executors.newSingleThreadExecutor(); Future<TaskResult> future = service.submit(task); TaskResult result = null; try { result = future.get(); } catch (InterruptedException | ExecutionException e) { result = new TaskResult("发生线程执行异常:" + e.getMessage()); } finally { service.shutdown(); } return result; } /** * 将执行结果集的异常信息转换为字符串 * * @param results 执行结果集 * @return 执行结果集转换为字符串 */ public static String toStringTaskResult(List<TaskResult> results) { if (CollectionUtils.isEmpty(results)) { return null; } StringBuffer sb = new StringBuffer(); for (TaskResult result : results) { if (StringUtil.isNotBlank(result.getError())) { sb.append(result.getError() + "\n"); } } return sb.toString(); } }
package xxx.task; import java.io.Serializable; import com.xxx.cip.common.util.builder.EqualsBuilder; import com.xxx.cip.common.util.builder.HashCodeBuilder; import com.xxx.cip.common.util.builder.ReflectionToStringBuilder; import com.xxx.cip.common.util.builder.ToStringStyle; import com.xxx.cip.json.JSONObject; /** * 任务结果集 * * @author 许畅 * @since JDK1.7 * @version 2017年5月10日 许畅 新建 */ public class TaskResult implements Serializable { /** serialVersionUID */ private static final long serialVersionUID = -1; /** * 构造方法 */ public TaskResult() { } /** * 构造方法 * * @param error 错误信息 */ public TaskResult(String error) { setError(error); setMessage(error); setSuccess(false); } /** 成功信息 */ private String message; /** 失败信息 */ private String error; /** 是否成功 */ private boolean success; /** JSON对象 */ private JSONObject jsonObj; /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the error */ public String getError() { return error; } /** * @param error the error to set */ public void setError(String error) { this.error = error; } /** * @return the success */ public boolean isSuccess() { return success; } /** * @param success the success to set */ public void setSuccess(boolean success) { this.success = success; } /** * 比较对象是否相等 * * @param objValue 比较对象 * @return 对象是否相等 * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object objValue) { return super.equals(objValue) ? true : EqualsBuilder.reflectionEquals(this, objValue); } /** * 生成hashCode * * @return hashCode值 * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * 通用toString * * @return 类信息 */ @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE); } /** * @return the jsonObj */ public JSONObject getJsonObj() { return jsonObj; } /** * @param jsonObj the jsonObj to set */ public void setJsonObj(JSONObject jsonObj) { this.jsonObj = jsonObj; } }
线程任务现实类:
package xxx.task; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import xxx.bm.metadata.base.model.BaseModel; /** * 编译代码任务 * * @author 许畅 * @since JDK1.7 * @version 2017年5月10日 许畅 新建 */ public class CompileCodeTask implements Callable<TaskResult> { /** 工程路径集合 */ private final Set<String> projectPaths; /** 元数据对象 */ private final BaseModel metadata; /** 工程相对路径 */ private final String projectRelativePath; /** 包路径集合 */ private final List<String> packagePaths; /** * 构造方法 * * @param projectPaths 工程路径集合 * @param metadata 元数据对象 * @param projectRelativePath 项目的相对路径,如src/main/webapp * @param packagePaths 包路径集合 */ public CompileCodeTask(Set<String> projectPaths, BaseModel metadata, String projectRelativePath, List<String> packagePaths) { this.projectPaths = projectPaths; this.metadata = metadata; this.projectRelativePath = projectRelativePath; this.packagePaths = packagePaths; } /** * 调用代码编译功能 * * @return 任务结果集 * @throws Exception 异常 * * @see java.util.concurrent.Callable#call() */ @Override public TaskResult call() throws Exception { boolean isSuccess = CompileCodeClient.executeBuilderProject(projectPaths, metadata, projectRelativePath, packagePaths); TaskResult result = new TaskResult(); result.setSuccess(isSuccess); result.setMessage(isSuccess ? "编译成功" : "编译失败"); result.setError(isSuccess ? "" : "编译失败"); return result; } /** * @return the projectPaths */ public Set<String> getProjectPaths() { return projectPaths; } /** * @return the metadata */ public BaseModel getMetadata() { return metadata; } /** * @return the projectRelativePath */ public String getProjectRelativePath() { return projectRelativePath; } /** * @return the packagePaths */ public List<String> getPackagePaths() { return packagePaths; } }