在項目中為了提高大并發量時的性能穩定性,經常會使用到線程池來做多線程異步操作,多線程有2種,一種是實現runnable接口,這種沒有返回值,一種是實現Callable接口,這種有返回值。
當其中一個線程超時的時候,理論上應該不 影響其他線程的執行結果,但是在項目中出現的問題表明一個線程阻塞,其他線程返回的接口都為空。其實是個很簡單的問題,但是由于第一次碰到,還是想了一些時間的。很簡單,就是因為阻塞的那個線
程沒有釋放,并發量一大,線程池數量就滿了,所以其他線程都處于等待狀態。
附上一段自己寫的調試代碼,當想不出問題的時候,自己模擬的寫寫,說不定問題就出來了。
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 { // 開始執行耗時操作 Thread.sleep( 1000 * 2 ); return "1線程執行完成." ; } }; Callable<String> call2 = new Callable<String>() { public String call() throws Exception { // 開始執行耗時操作 // Thread.sleep(1000 * 5); return "2線程執行完成." ; } }; Callable<String> call3 = new Callable<String>() { public String call() throws Exception { // 開始執行耗時操作 // Thread.sleep(1000 * 5); return "3線程執行完成." ; } }; 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); // 任務處理超時時間設為 } // 1 秒 catch (Exception e){ System.out.println( "處理超時啦...." ); e.printStackTrace(); } try { obj3 = future3.get( 3000 , TimeUnit.MILLISECONDS); // 任務處理超時時間設為 } // 1 秒 catch (Exception e){ System.out.println( "處理超時啦...." ); e.printStackTrace(); } try { obj2 = future2.get( 3000 , TimeUnit.MILLISECONDS);} catch (Exception e){ System.out.println( "處理超時啦...." ); e.printStackTrace(); } System.out.println( "3任務成功返回:" + obj3); System.out.println( "2任務成功返回:" + obj2); System.out.println( "1任務成功返回:" + obj); exec.shutdown(); } } |
以上就是小編為大家帶來的淺談java中異步多線程超時導致的服務異常全部內容了,希望大家多多支持服務器之家~