很多時(shí)候我們都希望能夠最大的利用資源,比如在進(jìn)行io操作的時(shí)候盡可能的避免同步阻塞的等待,因?yàn)檫@會(huì)浪費(fèi)cpu的資源。如果在有可讀的數(shù)據(jù)的時(shí)候能夠通知程序執(zhí)行讀操作甚至由操作系統(tǒng)內(nèi)核幫助我們完成數(shù)據(jù)的拷貝,這再好不過了。從nio到completablefuture、lambda、fork/join,java一直在努力讓程序盡可能變的異步甚至擁有更高的并行度,這一點(diǎn)一些函數(shù)式語言做的比較好,因此java也或多或少的借鑒了某些特性。下面介紹一種非常常用的實(shí)現(xiàn)異步操作的方式。
考慮有一個(gè)耗時(shí)的操作,操作完后會(huì)返回一個(gè)結(jié)果(不管是正常結(jié)果還是異常),程序如果想擁有比較好的性能不可能由線程去等待操作的完成,而是應(yīng)該采用listener模式。jdk并發(fā)包里的future代表了未來的某個(gè)結(jié)果,當(dāng)我們向線程池中提交任務(wù)的時(shí)候會(huì)返回該對象。代碼例子:
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代表了線程執(zhí)行完以后的結(jié)果,可以通過future獲得執(zhí)行的結(jié)果 // 但是jdk1.8之前的future有點(diǎn)雞肋,并不能實(shí)現(xiàn)真正的異步,需要阻塞的獲取結(jié)果,或者不斷的輪詢 // 通常我們希望當(dāng)線程執(zhí)行完一些耗時(shí)的任務(wù)后,能夠自動(dòng)的通知我們結(jié)果,很遺憾這在原生jdk1.8之前 // 是不支持的,但是我們可以通過第三方的庫實(shí)現(xiàn)真正的異步回調(diào) 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" ); } } |
如果想獲得耗時(shí)操作的結(jié)果,可以通過get方法獲取,但是該方法會(huì)阻塞當(dāng)前線程,我們可以在做完剩下的某些工作的時(shí)候調(diào)用get方法試圖去獲取結(jié)果,也可以調(diào)用非阻塞的方法isdone來確定操作是否完成,這種方式有點(diǎn)兒類似下面的過程:
這種方式對流程的控制很混亂,但是在jdk1.8之前只提供了這種笨拙的實(shí)現(xiàn)方式,以至于很多高性能的框架都實(shí)現(xiàn)了自己的一套異步框架,比如netty和guava,下面分別介紹下這三種異步的實(shí)現(xiàn)方式(包括jdk1.8)。首先是guava中的實(shí)現(xiàn)方式:
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.common.util.concurrent.futurecallback; import com.google.common.util.concurrent.futures; import com.google.common.util.concurrent.listenablefuture; import com.google.common.util.concurrent.listeningexecutorservice; import com.google.common.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); //向線程池中提交一個(gè)任務(wù)后,將會(huì)返回一個(gè)可監(jiān)聽的future,該future由guava框架提供 listenablefuture<string> lf = listeningexecutor.submit( new callable<string>() { @override public string call() throws exception { system.out.println( "task started!" ); //模擬耗時(shí)操作 thread.sleep( 3000 ); system.out.println( "task finished!" ); return "hello" ; } }); //添加回調(diào),回調(diào)由executor中的線程觸發(fā),但也可以指定一個(gè)新的線程 futures.addcallback(lf, new futurecallback<string>() { //耗時(shí)任務(wù)執(zhí)行失敗后回調(diào)該方法 @override public void onfailure(throwable t) { system.out.println( "failure" ); } //耗時(shí)任務(wù)執(zhí)行成功后回調(diào)該方法 @override public void onsuccess(string s) { system.out.println( "success " + s); } }); //主線程可以繼續(xù)做其他的工作 system.out.println( "main thread is running" ); } } |
guava提供了一套完整的異步框架,核心是可監(jiān)聽的future,通過注冊監(jiān)聽器或者回調(diào)方法實(shí)現(xiàn)及時(shí)獲取操作結(jié)果的能力。需要提一點(diǎn)的是,假設(shè)添加監(jiān)聽的時(shí)候耗時(shí)操作已經(jīng)執(zhí)行完了,此時(shí)回調(diào)方法會(huì)被立即執(zhí)行并不會(huì)丟失。想探究其實(shí)現(xiàn)方式的話可以跟一下源碼,底層的原理并不難。
談到異步編程就不得不提一下promise,很多函數(shù)式語言比如js原生支持promise,但是在java界也有一些promise框架,其中就有大名鼎鼎的netty。從future、callback到promise甚至線程池,netty實(shí)現(xiàn)了一套完整的異步框架,并且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 ); //向線程池中提交任務(wù),并返回future,該future是netty自己實(shí)現(xiàn)的future //位于io.netty.util.concurrent包下,此處運(yùn)行時(shí)的類型為promisetask future<?> f = group.submit( new runnable() { @override public void run() { system.out.println( "任務(wù)正在執(zhí)行" ); //模擬耗時(shí)操作,比如io操作 try { thread.sleep( 1000 ); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println( "任務(wù)執(zhí)行完畢" ); } }); //增加監(jiān)聽 f.addlistener( new futurelistener() { @override public void operationcomplete(future arg0) throws exception { system.out.println( "ok!!!" ); } }); system.out.println( "main thread is running." ); } } |
直到j(luò)dk1.8才算真正支持了異步操作,其中借鑒了某些框架的實(shí)現(xiàn)思想,但又有新的功能,同時(shí)在jdk1.8中提供了lambda表達(dá)式,使得java向函數(shù)式語言又靠近了一步。借助jdk原生的completablefuture可以實(shí)現(xiàn)異步的操作,同時(shí)結(jié)合lambada表達(dá)式大大簡化了代碼量。代碼例子如下:
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.completablefuture; import java.util.concurrent.executionexception; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.function.supplier; /** * 基于jdk1.8實(shí)現(xiàn)任務(wù)異步處理 * * @author administrator * */ public class javapromise { public static void main(string[] args) throws throwable, executionexception { // 兩個(gè)線程的線程池 executorservice executor = executors.newfixedthreadpool( 2 ); //jdk1.8之前的實(shí)現(xiàn)方式 completablefuture<string> future = completablefuture.supplyasync( new supplier<string>() { @override public string get() { system.out.println( "task started!" ); try { //模擬耗時(shí)操作 thread.sleep( 2000 ); } catch (interruptedexception e) { e.printstacktrace(); } return "task finished!" ; } }, executor); //采用lambada的實(shí)現(xiàn)方式 future.thenaccept(e -> system.out.println(e + " ok" )); system.out.println( "main thread is running" ); } } |
上面的圖只是簡單的表示了一下異步的實(shí)現(xiàn)流程,實(shí)際的調(diào)用中看似順序的步驟會(huì)發(fā)生線程的切換。
以上所述是小編給大家介紹的java異步編程詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!