這篇文章主要介紹“怎么使用Java編寫超時(shí)工具類”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“怎么使用Java編寫超時(shí)工具類”文章能幫助大家解決問(wèn)題。
創(chuàng)新互聯(lián)專注于西城企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,購(gòu)物商城網(wǎng)站建設(shè)。西城網(wǎng)站建設(shè)公司,為西城等地區(qū)提供建站服務(wù)。全流程按需設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
1、說(shuō)明
java已經(jīng)為我們提供了解決辦法。jdk1.5帶來(lái)的并發(fā)庫(kù)Future類可以滿足這一需求。Future類中重要的方法有g(shù)et()和cancel()。get()獲取數(shù)據(jù)對(duì)象,如果數(shù)據(jù)沒(méi)有加載,則在獲取數(shù)據(jù)之前堵塞,cancel()取消數(shù)據(jù)加載。另一個(gè)get(timeout)操作表明,如果timeout時(shí)間內(nèi)沒(méi)有得到,就會(huì)失敗回來(lái),不會(huì)堵塞。
利用泛型和函數(shù)式接口編寫一個(gè)工具類,可以讓超時(shí)處理更方便,而不用到處寫代碼。
2、實(shí)例
/** * TimeoutUtil <br> * * @author lys * @date 2021/2/25 */ @Slf4j @Component @NoArgsConstructor public class TimeoutUtil { private ExecutorService executorService; public TimeoutUtil(ExecutorService executorService) { this.executorService = executorService; } /** * 有超時(shí)限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(shù) * @param timeout 超時(shí)時(shí)間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, int timeout) { return doWithTimeLimit(bizSupplier, null, timeout); } /** * 有超時(shí)限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(shù) * @param defaultResult 默認(rèn)值 * @param timeout 超時(shí)時(shí)間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, R defaultResult, int timeout) { R result; String errMsg = "Null value"; FutureTask<R> futureTask = new FutureTask<>(bizSupplier::get); executorService.execute(futureTask); try { result = futureTask.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { errMsg = String.format("doWithTimeLimit執(zhí)行超過(guò)%d毫秒,強(qiáng)制結(jié)束", timeout); log.error(errMsg, e); futureTask.cancel(true); result = defaultResult; } return of(result, errMsg); } /** * 隨機(jī)耗時(shí)的測(cè)試方法 */ private String randomSpentTime() { Random random = new Random(); int time = (random.nextInt(10) + 1) * 1000; log.info("預(yù)計(jì)randomSpentTime方法執(zhí)行將耗時(shí): " + time + "毫秒"); try { Thread.sleep(time); } catch (Exception e) { } return "randomSpentTime --> " + time; } public static void main(String[] args) throws Exception { ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), runnable -> { Thread thread = new Thread(runnable); // 以守護(hù)線程方式啟動(dòng) thread.setDaemon(true); return thread; }); TimeoutUtil timeoutUtil = new TimeoutUtil(executorService); for (int i = 1; i <= 10; i++) { log.info("\n=============第{}次超時(shí)測(cè)試=============", i); Thread.sleep(6000); long start = System.currentTimeMillis(); String result = timeoutUtil.doWithTimeLimit(() -> timeoutUtil.randomSpentTime(), 5000).getOrElse("默認(rèn)"); log.info("doWithTimeLimit方法實(shí)際耗時(shí){}毫秒,結(jié)果:{}", System.currentTimeMillis() - start, result); } } }
關(guān)于“怎么使用Java編寫超時(shí)工具類”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。
文章名稱:怎么使用Java編寫超時(shí)工具類
本文URL:http://m.kartarina.com/article36/jeccpg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、全網(wǎng)營(yíng)銷推廣、App開(kāi)發(fā)、定制網(wǎng)站、網(wǎng)站設(shè)計(jì)公司、虛擬主機(jī)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)