JAVA 多线程执行

public class ThreadPoolUtils implements InitializingBean {
    ThreadPoolExecutor executor;

    int threadSize;
    int maximumPoolSize;
    long keepAliveTime;
    int maxQueueSize;

    @Override
    public void afterPropertiesSet() throws Exception {
        BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(maxQueueSize, true);
        executor = new ThreadPoolExecutor(threadSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, taskQueue);
    }



public class CreateOrderInvoker implements Callable<String> {
    private OrderService service;
    private OrderParam param;
    private CountDownLatch countDownLatch;

    public CreateOrderInvoker(OrderService service, OrderParam param) {
        this.service = service;
        this.param = param;
    }

    @Override
    public String call() throws Exception {
        String value= service.createOrder(param);
        countDownLatch.countDown();
        return value;
    }

    public void test(){
        List<FutureTask<String>> futureTasks = new ArrayList<FutureTask<String>>(10);
        ThreadPoolUtils poolUtils = new ThreadPoolUtils();
        for (int i = 0;  i < 10; i++) {
            CreateOrderInvoker invoker = new CreateOrderInvoker(null,null);
            FutureTask<String> futureTask = new FutureTask<String>(invoker);
            try {
                poolUtils.getExecutor().execute(futureTask);
                futureTasks.add(futureTask);
            } catch (Exception e) {
            }
        }

        // 3 获取各个createPayOrder的接口
        boolean concurrentResult = false;
        try {
            concurrentResult = countDownLatch.await(25, TimeUnit.SECONDS);//多线程执行设定超时时间
            if (concurrentResult) {
                System.out.println("批量创建成功,尚未返回的创建结果的有{}个"+ countDownLatch.getCount());
            } else {
                System.out.println("批量创建有超时,尚未返回创建结果的有{}个。参数是:{}", countDownLatch.getCount(), JSON.toJSONString(param));
            }
        } catch (Throwable e) {

        }

        poolUtils.getExecutor().submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行具体的任务");
            }
        });
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值