在項(xiàng)目中為了提高大并發(fā)量時(shí)的性能穩(wěn)定性,經(jīng)常會使用到線程池來做多線程異步操作,多線程有2種,一種是實(shí)現(xiàn)runnable接口,這種沒有返回值,一種是實(shí)現(xiàn)Callable接口,這種有返回值。
當(dāng)其中一個(gè)線程超時(shí)的時(shí)候,理論上應(yīng)該不 影響其他線程的執(zhí)行結(jié)果,但是在項(xiàng)目中出現(xiàn)的問題表明一個(gè)線程阻塞,其他線程返回的接口都為空。其實(shí)是個(gè)很簡單的問題,但是由于第一次碰到,還是想了一些時(shí)間的。很簡單,就是因?yàn)樽枞哪莻€(gè)線
程沒有釋放,并發(fā)量一大,線程池?cái)?shù)量就滿了,所以其他線程都處于等待狀態(tài)。
附上一段自己寫的調(diào)試代碼,當(dāng)想不出問題的時(shí)候,自己模擬的寫寫,說不定問題就出來了。
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
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; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class FutureTest { public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { final ExecutorService exec = Executors.newFixedThreadPool( 1 ); Callable<String> call = new Callable<String>() { public String call() throws InterruptedException { // 開始執(zhí)行耗時(shí)操作 Thread.sleep( 1000 * 2 ); return "1線程執(zhí)行完成." ; } }; Callable<String> call2 = new Callable<String>() { public String call() throws Exception { // 開始執(zhí)行耗時(shí)操作 // Thread.sleep(1000 * 5); return "2線程執(zhí)行完成." ; } }; Callable<String> call3 = new Callable<String>() { public String call() throws Exception { // 開始執(zhí)行耗時(shí)操作 // Thread.sleep(1000 * 5); return "3線程執(zhí)行完成." ; } }; Future<String> future = exec.submit(call); Future<String> future3 = exec.submit(call3); Future<String> future2 = exec.submit(call2); String obj= "" ; String obj2 = "" ; String obj3 = "" ; try { obj = future.get( 500 , TimeUnit.MILLISECONDS); // 任務(wù)處理超時(shí)時(shí)間設(shè)為 } // 1 秒 catch (Exception e){ System.out.println( "處理超時(shí)啦...." ); e.printStackTrace(); } try { obj3 = future3.get( 3000 , TimeUnit.MILLISECONDS); // 任務(wù)處理超時(shí)時(shí)間設(shè)為 } // 1 秒 catch (Exception e){ System.out.println( "處理超時(shí)啦...." ); e.printStackTrace(); } try { obj2 = future2.get( 3000 , TimeUnit.MILLISECONDS);} catch (Exception e){ System.out.println( "處理超時(shí)啦...." ); e.printStackTrace(); } System.out.println( "3任務(wù)成功返回:" + obj3); System.out.println( "2任務(wù)成功返回:" + obj2); System.out.println( "1任務(wù)成功返回:" + obj); exec.shutdown(); } } |
以上就是小編為大家?guī)淼臏\談java中異步多線程超時(shí)導(dǎo)致的服務(wù)異常全部內(nèi)容了,希望大家多多支持服務(wù)器之家~