一、Future模式

Java 1.5开始,提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。

Future接口可以构建异步应用,是多线程开发中常见的设计模式。

当我们需要调用一个函数方法时。如果这个函数执行很慢,那么我们就要进行等待。但有时候,我们可能并不急着要结果。

因此,我们可以让被调用者立即返回,让他在后台慢慢处理这个请求。对于调用者来说,则可以先处理一些其他任务,在真正需要数据的场合再去尝试获取需要的数据。

1、Callable与Runnable

java.lang.Runnable是一个接口,在它里面只声明了一个run()方法,run返回值是void,任务执行完毕后无法返回任何结果

public interface Runnable {
public abstract void run();
}

Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法叫做call(),这是一个泛型接口,call()函数返回的类型就是传递进来的V类型

public interface Callable<V> {
V call() throws Exception;
}

2、Future + Callable

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果

public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}

怎么使用Future和Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

Future+Callable,使用示例如下(采用第一个方法):


import java.util.Random;
import java.util.concurrent.*; /**
* @program: callable
* @description: Test
* @author: Mr.Wang
* @create: 2018-08-12 11:37
**/
public class MyTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Future<Integer> result = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt();
}
});
executor.shutdown(); try {
System.out.println("result:" + result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} }

结果:

result:297483790

其它方式:

import java.util.Random;
import java.util.concurrent.*; /**
* @program: callable
* @description: testfuture
* @author: Mr.Wang
* @create: 2018-08-12 12:11
**/
public class Testfuture {
public static void main(String[] args){
//第一种方式
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return new Random().nextInt();
}
});
new Thread(task).start();
//第二种方方式
// ExecutorService executor = Executors.newSingleThreadExecutor();
// FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
// @Override
// public Integer call() throws Exception {
// return new Random().nextInt();
// }
// });
// executor.submit(task); try {
System.out.println("result: "+task.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} }
result:-358490809

3、Future 接口的局限性

了解了Future的使用,这里就要谈谈Future的局限性。Future很难直接表述多个Future 结果之间的依赖性,开发中,我们经常需要达成以下目的:

  • 将两个异步计算合并为一个(这两个异步计算之间相互独立,同时第二个又依赖于第一个的结果)
  • 等待 Future 集合中的所有任务都完成。
  • 仅等待 Future 集合中最快结束的任务完成,并返回它的结果。

二、CompletableFuture

首先,CompletableFuture类实现了CompletionStage和Future接口,因此你可以像Future那样使用它。

莫急,下面通过例子来一步一步解释CompletableFuture的使用。

创建CompletableFuture对象

说明:Async结尾的方法都是可以异步执行的,如果指定了线程池,会在指定的线程池中执行,如果没有指定,默认会在ForkJoinPool.commonPool()中执行。下面很多方法都是类似的,不再做特别说明。

四个静态方法用来为一段异步执行的代码创建CompletableFuture对象,方法的参数类型都是函数式接口,所以可以使用lambda表达式实现异步任务

runAsync方法:它以Runnabel函数式接口类型为参数,所以CompletableFuture的计算结果为空。

supplyAsync方法以Supplier<U>函数式接口类型为参数,CompletableFuture的计算结果类型为U。

public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

1、变换结果

public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn,Executor executor);

这些方法的输入是上一个阶段计算后的结果,返回值是经过转化后结果

例子:

import java.util.concurrent.CompletableFuture;

/**
* @program: callable
* @description: test
* @author: Mr.Wang
* @create: 2018-08-12 12:36
**/
public class TestCompleteFuture {
public static void main(String[] args){
String result = CompletableFuture.supplyAsync(()->{return "Hello ";}).thenApplyAsync(v -> v + "world").join();
System.out.println(result);
}
}

结果:

Hello world

2、消费结果

public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

这些方法只是针对结果进行消费,入参是Consumer,没有返回值

例子:

import java.util.concurrent.CompletableFuture;

/**
* @program: callable
* @description: test
* @author: Mr.Wang
* @create: 2018-08-12 12:36
**/
public class TestCompleteFuture {
public static void main(String[] args){
CompletableFuture.supplyAsync(()->{return "Hello ";}).thenAccept(v -> { System.out.println("consumer: " + v);});
}
}

结果:

consumer: Hello 

3、结合两个CompletionStage的结果,进行转化后返回

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);

需要上一阶段的返回值,并且other代表的CompletionStage也要返回值之后,把这两个返回值,进行转换后返回指定类型的值。

说明:同样,也存在对两个CompletionStage结果进行消耗的一组方法,例如thenAcceptBoth,这里不再进行示例。

例子:

import java.util.concurrent.CompletableFuture;

/**
* @program: callable
* @description: test
* @author: Mr.Wang
* @create: 2018-08-12 12:36
**/
public class TestCompleteFuture {
public static void main(String[] args){ String result = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello";
}).thenCombine(CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}),(s1,s2)->{return s1 + " " + s2;}).join();
System.out.println(result);
}
}

结果:

Hello world

4、两个CompletionStage,谁计算的快,就用那个CompletionStage的结果进行下一步的处理

public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);

两种渠道完成同一个事情,就可以调用这个方法,找一个最快的结果进行处理,最终有返回值。

例子:

import java.util.concurrent.CompletableFuture;

/**
* @program: callable
* @description: test
* @author: Mr.Wang
* @create: 2018-08-12 12:36
**/
public class TestCompleteFuture {
public static void main(String[] args){ String result = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hi Boy";
}).applyToEither(CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hi Girl";
}),(s)->{return s;}).join();
System.out.println(result);
}
}

结果:

Hi Boy

5、运行时出现了异常,可以通过exceptionally进行补偿

public CompletionStage<T> exceptionally(Function<Throwable, ? extends T> fn);

例子:

import java.util.concurrent.CompletableFuture;

/**
* @program: callable
* @description: test
* @author: Mr.Wang
* @create: 2018-08-12 12:36
**/
public class TestCompleteFuture {
public static void main(String[] args){ String result = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(true) {
throw new RuntimeException("exception test!");
} return "Hi Boy";
}).exceptionally(e->{
System.out.println(e.getMessage());
return "Hello world!";
}).join();
System.out.println(result);
}
}

结果:

java.lang.RuntimeException: exception test!
Hello world!

三、结束

OK,了解了以上使用,基本上就对CompletableFuture比较清楚了。

后面会找个时间说说CompletableFuture实现原理

Java并发编程系列一:Future和CompletableFuture解析与使用的更多相关文章

  1. Java并发编程系列-(9) JDK 8/9/10中的并发

    9.1 CompletableFuture CompletableFuture是JDK 8中引入的工具类,实现了Future接口,对以往的FutureTask的功能进行了增强. 手动设置完成状态 Co ...

  2. Java并发编程系列-(2) 线程的并发工具类

    2.线程的并发工具类 2.1 Fork-Join JDK 7中引入了fork-join框架,专门来解决计算密集型的任务.可以将一个大任务,拆分成若干个小任务,如下图所示: Fork-Join框架利用了 ...

  3. Java并发编程系列-(6) Java线程池

    6. 线程池 6.1 基本概念 在web开发中,服务器需要接受并处理请求,所以会为一个请求来分配一个线程来进行处理.如果每次请求都新创建一个线程的话实现起来非常简便,但是存在一个问题:如果并发的请求数 ...

  4. 干货:Java并发编程系列之volatile(二)

    接上一篇<Java并发编程系列之synchronized(一)>,这是第二篇,说的是关于并发编程的volatile元素. Java语言规范第三版中对volatile的定义如下:Java编程 ...

  5. Java并发编程系列-(5) Java并发容器

    5 并发容器 5.1 Hashtable.HashMap.TreeMap.HashSet.LinkedHashMap 在介绍并发容器之前,先分析下普通的容器,以及相应的实现,方便后续的对比. Hash ...

  6. Java并发编程系列-(4) 显式锁与AQS

    4 显示锁和AQS 4.1 Lock接口 核心方法 Java在java.util.concurrent.locks包中提供了一系列的显示锁类,其中最基础的就是Lock接口,该接口提供了几个常见的锁相关 ...

  7. Java并发编程系列-(3) 原子操作与CAS

    3. 原子操作与CAS 3.1 原子操作 所谓原子操作是指不会被线程调度机制打断的操作:这种操作一旦开始,就一直运行到结束,中间不会有任何context switch,也就是切换到另一个线程. 为了实 ...

  8. Java并发编程系列-(1) 并发编程基础

    1.并发编程基础 1.1 基本概念 CPU核心与线程数关系 Java中通过多线程的手段来实现并发,对于单处理器机器上来讲,宏观上的多线程并行执行是通过CPU的调度来实现的,微观上CPU在某个时刻只会运 ...

  9. Java并发编程系列-(7) Java线程安全

    7. 线程安全 7.1 线程安全的定义 如果多线程下使用这个类,不过多线程如何使用和调度这个类,这个类总是表示出正确的行为,这个类就是线程安全的. 类的线程安全表现为: 操作的原子性 内存的可见性 不 ...

  10. Java并发编程系列-(8) JMM和底层实现原理

    8. JMM和底层实现原理 8.1 线程间的通信与同步 线程之间的通信 线程的通信是指线程之间以何种机制来交换信息.在编程中,线程之间的通信机制有两种,共享内存和消息传递. 在共享内存的并发模型里,线 ...

随机推荐

  1. BZOJ1879:[SDOI2009]Bill的挑战(状压DP)

    Description Input 本题包含多组数据.  第一行:一个整数T,表示数据的个数.  对于每组数据:  第一行:两个整数,N和K(含义如题目表述).  接下来N行:每行一个字符串. T ≤ ...

  2. mac zsh 快捷定位文件

    brew install zsh vim ~/.zshrc plugins=(git autojump zsh-autosuggestions zsh-syntax-highlighting yarn ...

  3. Kali-linux设置ProxyChains

    ProxyChains是Linux和其他Unices下的代理工具.它可以使任何程序通过代理上网,允许TCP和DNS通过代理隧道,支持HTTP.SOCKS4和SOCKS5类型的代理服务器,并且可配置多个 ...

  4. Lambda使用

    说明 本文内容来自 [Java8 In Action] 一书 四种方法引用类型 类型 示例 引用静态方法 ContainingClass::staticMethodName 引用某个对象的实例方法 c ...

  5. usb入门学习

    1.学习资源: usb org.http://www.beyondlogic.org/usbnutshell/usb3.shtml http://wenku.baidu.com/view/028231 ...

  6. MySql第几行到第几行语句

    1.查询第一行记录: select * from table limit 1 2.查询第n行到第m行记录 select * from table1 limit n-1,m-n; SELECT * FR ...

  7. 史上最简单的SpringCloud教程 | 第十篇: 高可用的服务注册中心(Finchley版本)

    转载请标明出处: 原文首发于 https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f10-eureka/ 本文出自方志朋的博客 文章 史上最简单 ...

  8. Jstorm+Spring+mybatis整合

    在现有的jstorm框架下,有一个需求:jstorm要对接mysql数据库的实时读取数据, 通过bolt处理,可能要调用service层的框架,最后保存到数据库. 在网上寻找了一下,发现storm集成 ...

  9. python函数调用时传参方式

    位置参数 位置参数需与形参一一对应 def test(a,b) #a,b就是位置参数 print(a) print(b) test(1,2)   关键字参数 与形参顺序无关 def test(x,y) ...

  10. js 获取任意一个元素的任意一个样式属性的值

    //谷歌,火狐支持console.log(window.getComputedStyle(my$("dv"),null).left);//IE8支持console.log(my$( ...