美文网首页
Java中的Future & Callable

Java中的Future & Callable

作者: akka_dell | 来源:发表于2016-07-31 12:42 被阅读0次

    最简单的基本流程是:

    1. Callable任务通过ExecutorService来提交;
    2. 任务结束后返回的结果交给Future;
    3. Future通过get()方法去获得实际的运算结果。
    
    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;
    
    class Merge implements Callable<String>{
        
        private String strA;
        private String strB;
        
        Merge(String strA, String strB){
            this.strA = strA;
            this.strB = strB;
        }
    
        @Override
        public String call() throws Exception {
            return strA+strB;
        }
        
    }
    
    public class CallableTest {
    
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            ExecutorService es = Executors.newFixedThreadPool(1);
            Merge task = new Merge("Hello " ,"World!");
            Future<String> future = es.submit(task);
            String result = future.get();
            System.out.println(result);
    
            es.shutdown();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Java中的Future & Callable

          本文链接:https://www.haomeiwen.com/subject/dbntsttx.html