在項目中為了提高大并發(fā)量時的性能穩(wěn)定性,經(jīng)常會使用到線程池來做多線程異步操作,多線程有2種,一種是實現(xiàn)runnable接口,這種沒有返回值,一種是實現(xiàn)Callable接口,這種有返回值。
當(dāng)其中一個線程超時的時候,理論上應(yīng)該不 影響其他線程的執(zhí)行結(jié)果,但是在項目中出現(xiàn)的問題表明一個線程阻塞,其他線程返回的接口都為空。其實是個很簡單的問題,但是由于第一次碰到,還是想了一些時間的。很簡單,就是因為阻塞的那個線
程沒有釋放,并發(fā)量一大,線程池數(shù)量就滿了,所以其他線程都處于等待狀態(tài)。
附上一段自己寫的調(diào)試代碼,當(dāng)想不出問題的時候,自己模擬的寫寫,說不定問題就出來了。
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í)行耗時操作 Thread.sleep(1000 * 2); return "1線程執(zhí)行完成."; } }; Callable<String> call2 = new Callable<String>() { public String call() throws Exception { // 開始執(zhí)行耗時操作 // Thread.sleep(1000 * 5); return "2線程執(zhí)行完成."; } }; Callable<String> call3 = new Callable<String>() { public String call() throws Exception { // 開始執(zhí)行耗時操作 // 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è)為 }// 1 秒 catch(Exception e){ System.out.println("處理超時啦...."); e.printStackTrace(); } try{ obj3 = future3.get(3000, TimeUnit.MILLISECONDS); // 任務(wù)處理超時時間設(shè)為 }// 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任務(wù)成功返回:" + obj3); System.out.println("2任務(wù)成功返回:" + obj2); System.out.println("1任務(wù)成功返回:" + obj); exec.shutdown(); } }以上就是小編為大家?guī)淼臏\談java中異步多線程超時導(dǎo)致的服務(wù)異常全部內(nèi)容了,希望大家多多支持武林網(wǎng)~
新聞熱點(diǎn)
疑難解答
圖片精選