Java多线程Future task的使用

处理批量任务 :

本文

转载地址 : http://blog.csdn.net/u010963948/article/details/54669708

先直接上代码如下:

一、需要实现Callable接口(可以使用泛型)

[java]  view plain  copy
  1. package com.innotek.spms.service.finance;  
  2.   
  3. import com.innotek.common.util.SpringContextUtil;  
  4. import com.innotek.spms.entity.busi.Collector;  
  5. import com.innotek.spms.entity.busi.Payment;  
  6. import com.innotek.spms.entity.fanc.PaymentCard;  
  7. import com.innotek.spms.entity.swap.OwefeeRecord;  
  8. import com.innotek.spms.entity.swap.RepayRecord;  
  9. import com.innotek.spms.entity.tran.PayOrder;  
  10. import com.innotek.spms.service.PayBackService;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12.   
  13. import java.util.concurrent.Callable;  
  14.   
  15. public class RepayTask implements Callable<Long> {  
  16.   
  17.     private PayOrder payOrder;  
  18.     private Collector collector;  
  19.     private Payment payment;  
  20.     private String payAccount;  
  21.     private String cityCode;  
  22.     private OwefeeRecord owefeeRecord;  
  23.     private RepayRecord tempEntity;  
  24.     private long oweFee;  
  25.     private long paymentId;  
  26.     private PaymentCard card;  
  27.   
  28.     public RepayTask(PayOrder payOrder, Collector collector, Payment payment,  
  29.                      String payAccount, String cityCode, OwefeeRecord owefeeRecord, RepayRecord tempEntity,  
  30.                      long oweFee, long paymentId, PaymentCard card) {  
  31.   
  32.         this.payOrder=payOrder;  
  33.         this.collector=collector;  
  34.         this.payment=payment;  
  35.         this.payAccount=payAccount;  
  36.         this.cityCode=cityCode;  
  37.         this.owefeeRecord=owefeeRecord;  
  38.         this.tempEntity=tempEntity;  
  39.         this.oweFee=oweFee;  
  40.         this.paymentId=paymentId;  
  41.         this.card=card;  
  42.     }  
  43.   
  44.   
  45.     @Override  
  46.     public Long call() throws Exception {  
  47.         PayBackService payBackService=(PayBackService) SpringContextUtil.getBean("payBackService");  
  48.   
  49.         return    payBackService.eliminateRecordImpl(payOrder, collector, payment,  
  50.                 payAccount, cityCode, owefeeRecord, tempEntity, oweFee,  
  51.                 paymentId, card);  
  52.   
  53.   
  54.     }  
  55. }  

二、创建线程池使用:

[java]  view plain  copy
  1. // 线程执行补缴接口  
  2. ExecutorService executor= Executors.newCachedThreadPool();  
  3. List<RepayTask> taskList=new ArrayList<RepayTask>();  
  4. RepayTask task=new RepayTask(payOrder, collector, payment,  
  5.     payAccount, cityCode, owefeeRecord, tempEntity, oweFee,  
  6.     paymentIdFianl, card);  
  7. taskList.add(task);  
  8. List<Future<Long>>resultList=null;  
  9. try {  
  10.     //执行全部的线程  
  11.     resultList=executor.invokeAll(taskList);  
  12.     if(CollectionUtils.isNotEmpty(resultList)){  
  13.         for (int i=0; i<resultList.size(); i++){  
  14.             Future<Long> future=resultList.get(i);  
  15.             sum+=  future.get();  
  16.         }  
  17.     }  
  18. catch (Exception e) {  
  19.     e.printStackTrace();  
  20. }  

三、其他详解如下:

并发编程时,一般使用runnable,然后扔给线程池完事,这种情况下不需要线程的结果。 
所以run的返回值是void类型。 

如果是一个多线程协作程序,比如菲波拉切数列,1,1,2,3,5,8...使用多线程来计算。 
但后者需要前者的结果,就需要用callable接口了。 
callable用法和runnable一样,只不过调用的是call方法,该方法有一个泛型返回值类型,你可以任意指定。 

线程是属于异步计算模型,所以你不可能直接从别的线程中得到函数返回值。 
 这时候,Future就出场了。Futrue可以监视目标线程调用call的情况,当你调用Future的get()方法以获得结果时,当前线程就开始阻塞,直接call方法结束返回结果。 

下面三段简单的代码可以很简明的揭示这个意思: 
 
runnable接口实现的没有返回值的并发编程。 
 
callable实现的存在返回值的并发编程。(call的返回值String受泛型的影响) 
 
同样是callable,使用Future获取返回值。

package demo.future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 试验 Java 的 Future 用法
 */
public class FutureTest {

    public static class Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            String tid = String.valueOf(Thread.currentThread().getId());
            System.out.printf("Thread#%s : in call\n", tid);
            return tid;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Future<String>> results = new ArrayList<Future<String>>();
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i=0; i<100;i++)
            results.add(es.submit(new Task()));

        for(Future<String> res : results)
            System.out.println(res.get());
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值