Java多线程之Promise模式

来源:互联网 发布:ubuntu 锐速 编辑:程序博客网 时间:2024/05/21 01:50

参考文档:
Java多线程编程模式实战指南之Promise模式

今天看到《Java多线程编程模式实战指南之Promise模式》这篇文章,感觉不错,虽然以前也了解过 future 这个东东,但是理解不是那么深,联想起 jQuery 的 promise,决定按文档的代码尝试一下。下面粘出代码:

package com.yuzx.test.promise;import org.junit.Test;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;/** * Created by yuzx on 15-12-11. */public class PromiseTestMain {    private static class FtpClient {        private FtpClient() {        }        public static Future<FtpClient> newFtpClient(final String serverName, final String username, final String password) {            Callable<FtpClient> callable = new Callable<FtpClient>() {                @Override                public FtpClient call() throws Exception {                    System.out.println("work 1.");                    FtpClient ftpClient = new FtpClient();                    ftpClient.init(serverName, username, password);                    return ftpClient;                }            };            FutureTask<FtpClient> promise = new FutureTask<FtpClient>(callable);            new Thread(promise).start();            // 先给个承诺,将来拿这个承诺来找我            return promise;        }        private void init(String serverName, String username, String password) throws InterruptedException {            Thread.sleep(5000);        }        private void printWork2(int res) {            System.out.println("res is " + res);        }    }    // 另一件很费时的任务    private int work2() throws InterruptedException {        System.out.println("work 2.");        Thread.sleep(3000);        return 109;    }    /**     * 将耗时操作均封装为 Promise,并行执行耗时操作     *     * @throws InterruptedException     * @throws ExecutionException     */    @Test    public void doTest() throws InterruptedException, ExecutionException {        Future<FtpClient> promise = FtpClient.newFtpClient("10.0.3.242", "yuzx", "pAs$w0rd");        int res = work2();        promise.get().printWork2(res);        FtpClient ftpClient = null;        try {            // 获取初始化完毕的FTP客户端实例            ftpClient = promise.get();        } catch (InterruptedException e) {            ;        } catch (ExecutionException e) {            throw new RuntimeException(e);        }    }}

可以将耗时的操作都封装为 promise,并行执行 Task,那么整个 Job 所花的时间应该是耗时最长的 Task 的时间,而不是所有 Task 的时间和。

0 0