JDK中的多线程并发调用

使用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;

/**
 * 线程任务执行器
 * 
 * @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;

/**
 * 任务结果集
 * 
 * @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;


/**
 * 编译代码任务
 * 
 * @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;
    }
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDK7,Class.forName方法在高并发环境下可能存在线程安全问题。具体表现为多线程同时调用Class.forName方法时,可能会出现重复加载类的情况,导致类的静态代码块被重复执行。这种情况会导致程序出现各种异常,例如类初始化异常、单例被重复创建等。 这个问题的原因在于JDK7的Class对象缓存机制存在缺陷,当多个线程同时调用Class.forName方法时,可能会导致多个线程同时从缓存获取到同一个Class对象,从而导致类的静态代码块被重复执行。 以下是一个伪代码示例,用于复现这种情况: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestClassForName { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { executorService.submit(() -> { try { Class.forName("TestClass"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }); } executorService.shutdown(); } static class TestClass { static { System.out.println(Thread.currentThread().getName() + " init TestClass"); } } } ``` 在这个示例,我们创建了一个线程池,同时提交了100个任务,每个任务都会调用Class.forName方法加载TestClass类。TestClass类有一个静态代码块,用于输出当前线程的名称和初始化TestClass类的信息。 运行这段代码,可能会出现以下输出结果: ``` pool-1-thread-1 init TestClass pool-1-thread-2 init TestClass pool-1-thread-3 init TestClass pool-1-thread-4 init TestClass pool-1-thread-5 init TestClass pool-1-thread-6 init TestClass pool-1-thread-7 init TestClass pool-1-thread-7 init TestClass pool-1-thread-8 init TestClass pool-1-thread-9 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass ``` 可以看到,在高并发环境下,TestClass类的静态代码块被重复执行了多次,导致输出了重复的信息。 为了解决这个问题,可以使用类加载器来加载类,而不是直接调用Class.forName方法。另外,JDK8及以上版本已经修复了这个问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值