很多时候我们都希望能够最大的利用资源,比如在进行io操作的时候尽可能的避免同步阻塞的等待,因为这会浪费cpu的资源。如果在有可读的数据的时候能够通知程序执行读操作甚至由操作系统内核帮助我们完成数据的拷贝,这再好不过了。从nio到completablefuture、lambda、fork/join, java 一直在努力让程序尽可能变的异步甚至拥有更高的并行度,这一点一些函数式语言做的比较好,因此java也或多或少的借鉴了某些特性。下面介绍一种非常常用的实现异步操作的方式。
考虑有一个耗时的操作,操作完后会返回一个结果(不管是正常结果还是异常),程序如果想拥有比较好的性能不可能由线程去等待操作的完成,而是应该采用listener模式。jdk并发包里的future代表了未来的某个结果,当我们向线程池中提交任务的时候会返回该对象。代码例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/** * jdk1.8之前的future * * @author administrator * */ public class javafuture { public static void main(string[] args) throws throwable, executionexception { executorservice executor = executors.newfixedthreadpool( 1 ); // future代表了线程执行完以后的结果,可以通过future获得执行的结果 // 但是jdk1.8之前的future有点鸡肋,并不能实现真正的异步,需要阻塞的获取结果,或者不断的轮询 // 通常我们希望当线程执行完一些耗时的任务后,能够自动的通知我们结果,很遗憾这在原生jdk1.8之前 // 是不支持的,但是我们可以通过第三方的库实现真正的异步回调 future<string> f = executor.submit( new callable<string>() {
@override public string call() throws exception { system.out.println( "task started!" ); thread.sleep( 3000 ); system.out.println( "task finished!" ); return "hello" ; } });
//此处阻塞main线程 system.out.println(f.get()); system.out.println( "main thread is blocked" ); } } |
如果想获得耗时操作的结果,可以通过get方法获取,但是该方法会阻塞当前线程,我们可以在做完剩下的某些工作的时候调用get方法试图去获取结果,也可以调用非阻塞的方法isdone来确定操作是否完成,这种方式有点儿类似下面的过程:
这种方式对流程的控制很混乱,但是在jdk1.8之前只提供了这种笨拙的实现方式,以至于很多高性能的框架都实现了自己的一套异步框架,比如netty和guava,下面分别介绍下这三种异步的实现方式(包括jdk1.8)。首先是guava中的实现方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
package guava;
import java.util.concurrent.callable; import java.util.concurrent.executorservice; import java.util.concurrent.executors;
import com.google测试数据mon.util.concurrent.futurecallback; import com.google测试数据mon.util.concurrent.futures; import com.google测试数据mon.util.concurrent.listenablefuture; import com.google测试数据mon.util.concurrent.listeningexecutorservice; import com.google测试数据mon.util.concurrent.moreexecutors;
/** * guava中的future * * @author administrator * */ public class guavafuture { public static void main(string[] args) { executorservice executor = executors.newfixedthreadpool( 1 );
// 使用guava提供的moreexecutors工具类包装原始的线程池 listeningexecutorservice listeningexecutor = moreexecutors.listeningdecorator(executor); //向线程池中提交一个任务后,将会返回一个可监听的future,该future由guava框架提供 listenablefuture<string> lf = listeningexecutor.submit( new callable<string>() {
@override public string call() throws exception { system.out.println( "task started!" ); //模拟耗时操作 thread.sleep( 3000 ); system.out.println( "task finished!" ); return "hello" ; } }); //添加回调,回调由executor中的线程触发,但也可以指定一个新的线程 futures.addcallback(lf, new futurecallback<string>() {
//耗时任务执行失败后回调该方法 @override public void onfailure(throwable t) { system.out.println( "failure" ); }
//耗时任务执行成功后回调该方法 @override public void onsuccess(string s) { system.out.println( "success " + s); } });
//主线程可以继续做其他的工作 system.out.println( "main thread is running" ); } } |
guava提供了一套完整的异步框架,核心是可监听的future,通过注册监听器或者回调方法实现及时获取操作结果的能力。需要提一点的是,假设添加监听的时候耗时操作已经执行完了,此时回调方法会被立即执行并不会丢失。想探究其实现方式的话可以跟一下源码,底层的原理并不难。
谈到 异步编程 就不得不提一下promise,很多函数式语言比如js原生支持promise,但是在java界也有一些promise框架,其中就有大名鼎鼎的netty。从future、callback到promise甚至线程池,netty实现了一套完整的异步框架,并且netty代码中也大量使用了promise,下面是netty中的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package netty_promise;
import io.netty.util.concurrent.defaulteventexecutorgroup; import io.netty.util.concurrent.eventexecutorgroup; import io.netty.util.concurrent.future; import io.netty.util.concurrent.futurelistener;
/** * netty中的promise * * @author administrator * */ public class promisetest { @suppresswarnings ({ "unchecked" , "rawtypes" }) public static void main(string[] args) throws throwable { //线程池 eventexecutorgroup group = new defaulteventexecutorgroup( 1 ); //向线程池中提交任务,并返回future,该future是netty自己实现的future //位于io.netty.util.concurrent包下,此处运行时的类型为promisetask future<?> f = group.submit( new runnable() {
@override public void run() { system.out.println( "任务正在执行" ); //模拟耗时操作,比如io操作 try { thread.sleep( 1000 ); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println( "任务执行完毕" ); } }); //增加监听 f.addlistener( new futurelistener() { @override public void operationcomplete(future arg0) throws exception { system.out.println( "ok!!!" ); } }); system.out.println( "main thread is running." ); } } |
直到jdk1.8才算真正支持了异步操作,其中借鉴了某些框架的实现思想,但又有新的功能,同时在jdk1.8中提供了lambda表达式,使得java向函数式语言又靠近了一步。借助jdk原生的completablefuture可以实现异步的操作,同时结合lambada表达式大大简化了代码量。代码例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package netty_promise;
import java.util.concurrent测试数据pletablefuture; import java.util.concurrent.executionexception; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.function.supplier;
/** * 基于jdk1.8实现任务异步处理 * * @author administrator * */ public class javapromise { public static void main(string[] args) throws throwable, executionexception { // 两个线程的线程池 executorservice executor = executors.newfixedthreadpool( 2 ); //jdk1.8之前的实现方式 completablefuture<string> future = completablefuture.supplyasync( new supplier<string>() { @override public string get() { system.out.println( "task started!" ); try { //模拟耗时操作 thread.sleep( 2000 ); } catch (interruptedexception e) { e.printstacktrace(); } return "task finished!" ; } }, executor);
//采用lambada的实现方式 future.thenaccept(e -> system.out.println(e + " ok" ));
system.out.println( "main thread is running" ); } } |
上面的图只是简单的表示了一下异步的实现流程,实际的调用中看似顺序的步骤会发生线程的切换。
以上所述是小编给大家介绍的java异步编程详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!