多线程 Future

package src;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 多线程执行,异步获取结果
 * 
 * @author i-clarechen
 *
 */
public class AsyncThread {


    public static void main(String[] args) {
        AsyncThread t = new AsyncThread();
        List<Future<String>> futureList = new ArrayList<Future<String>>();
       
        t.generate(3, futureList);
        
        t.doOtherThings();
        
        t.getResult(futureList);
    }


    /**
     * 生成指定数量的线程,都放入future数组
     * 
     * @param threadNum
     * @param fList
     */
    public void generate(int threadNum, List<Future<String>> fList) {
        ExecutorService service = Executors.newFixedThreadPool(threadNum);
        for (int i = 0; i < threadNum; i++) {
            Future<String> f = service.submit(getJob(i));
           System.out.println("------ 向 fList 添加 的  future 对象为:" + f );
            fList.add(f);
        }
        service.shutdown();
    }


    /**
     * other things
     */
    public void doOtherThings() {
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println("do other thing number:" + i);
                Thread.sleep(1000 * (new Random().nextInt(10)));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 从future中获取线程结果,打印结果
     * 
     * @param fList
     */
    public void getResult(List<Future<String>> fList) {
        ExecutorService service = Executors.newSingleThreadExecutor();    //单线程模拟
        service.execute(getCollectJob(fList));
        //System.out.println("======getResult 获取结果全部结束=======");
        service.shutdown();
    }


    /**
     * 生成指定序号的线程对象
     * 
     * @param i
     * @return
     */
    public Callable<String> getJob(final int i) {
        final int time = new Random().nextInt(50);
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
            System.out.println("生成线程对象    Thread.sleep前  " +Thread.currentThread().getName());
           
                Thread.sleep(1000 * time);
                
                System.out.println(">>>>生成线程对象   Thread.sleep后  " +Thread.currentThread().getName()+"  ,  sleep time 为 :"+1000 * time+" >>>>  此次返回值为:" +"thread-" + i);
                return "thread-" + i;
            }
        };
    }


    /**
     * 生成结果收集线程对象
     * 
     * @param fList
     * @return
     */
    public Runnable getCollectJob(final List<Future<String>> fList) {
        return new Runnable() {
            public void run() {
           
                for (Future<String> future : fList) {
                    try {
                        while (true) {
                            if (future.isDone() && !future.isCancelled()) {
                                System.out.println("Future对象为:" +future+"      ,Future Result:   " + future.get()); //get()
                                break;
                            } else {
                                Thread.sleep(1000);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                
                System.out.println("======getCollectJob  获取结果全部结束=======");
            }
        };
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值