首页 > 代码库 > Java Callable并发编程模板

Java Callable并发编程模板

submit方法会产生Future对象,它用Callable返回结果的特定类型进行了参数化,可以用isDone()的方法来查询Future是否已经完成。当任务完成是,它具有一个结果,可以调用get()方法来获取该结果。

/**   * @Title: TaskWithResult.java * @Package zeze * @Description: TODO(用一句话描述该文件做什么) * @author A18ccms A18ccms_gmail_com   * @date 2017年2月8日 上午10:51:26 * @version V1.0   */package zeze;import java.util.ArrayList;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class CallableDemo {    public static void main(String[] args) {        ExecutorService exec = Executors.newCachedThreadPool();        ArrayList<Future<String>> results = new ArrayList<Future<String>>();        for (int i = 0; i < 10; i++) {            results.add(exec.submit(new TaskWithResult(i)));        }        for (Future<String> fs : results) {            try {                System.out.println(fs.get());            } catch (Exception e) {                System.err.println(e);            } finally {                exec.shutdown();            }        }    }}class TaskWithResult implements Callable<String> {    private int id;    public TaskWithResult(int id) {        this.id = id;    }    @Override    public String call() {        return "result of TaskWithResult " + id;    }}

用isDone()的方法来查询Future是否已经完成

boolean isDone = false;        while (!isDone) {            logger.info(Thread.currentThread().getName() + " 线程是否结束?"+ runningFlag+"; 队列大小=" + nextDepthQueue.size());            isDone = true;            for (Future<Object> future : futureList) {                if (!future.isDone()) {                    isDone = false;                    try {                        Thread.sleep(3000);                    } catch (InterruptedException e) {                    }                    break;                }            }        }

 

Java Callable并发编程模板