這篇文章主要介紹Java如何編寫超時工具類,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
我們提供的服務(wù)有:網(wǎng)站建設(shè)、成都網(wǎng)站制作、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、江山ssl等。為上千多家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的江山網(wǎng)站制作公司
1. 簡單,只需理解基本的概念,就可以編寫適合于各種情況的應(yīng)用程序;2. 面向?qū)ο螅?. 分布性,Java是面向網(wǎng)絡(luò)的語言;4. 魯棒性,java提供自動垃圾收集來進(jìn)行內(nèi)存管理,防止程序員在管理內(nèi)存時容易產(chǎn)生的錯誤。;5. 安全性,用于網(wǎng)絡(luò)、分布環(huán)境下的Java必須防止病毒的入侵。6. 體系結(jié)構(gòu)中立,只要安裝了Java運(yùn)行時系統(tǒng),就可在任意處理器上運(yùn)行。7. 可移植性,Java可以方便地移植到網(wǎng)絡(luò)上的不同機(jī)器。8.解釋執(zhí)行,Java解釋器直接對Java字節(jié)碼進(jìn)行解釋執(zhí)行。
1、說明
java已經(jīng)為我們提供了解決辦法。jdk1.5帶來的并發(fā)庫Future類可以滿足這一需求。Future類中重要的方法有g(shù)et()和cancel()。get()獲取數(shù)據(jù)對象,如果數(shù)據(jù)沒有加載,則在獲取數(shù)據(jù)之前堵塞,cancel()取消數(shù)據(jù)加載。另一個get(timeout)操作表明,如果timeout時間內(nèi)沒有得到,就會失敗回來,不會堵塞。
利用泛型和函數(shù)式接口編寫一個工具類,可以讓超時處理更方便,而不用到處寫代碼。
2、實例
/** * TimeoutUtil <br> * * @author lys * @date 2021/2/25 */ @Slf4j @Component @NoArgsConstructor public class TimeoutUtil { private ExecutorService executorService; public TimeoutUtil(ExecutorService executorService) { this.executorService = executorService; } /** * 有超時限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(shù) * @param timeout 超時時間,ms * @return 返回值 */ public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, int timeout) { return doWithTimeLimit(bizSupplier, null, timeout); } /** * 有超時限制的方法 * * @param bizSupplier 業(yè)務(wù)函數(shù) * @param defaultResult 默認(rèn)值 * @param timeout 超時時間,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í)行超過%d毫秒,強(qiáng)制結(jié)束", timeout); log.error(errMsg, e); futureTask.cancel(true); result = defaultResult; } return of(result, errMsg); } /** * 隨機(jī)耗時的測試方法 */ private String randomSpentTime() { Random random = new Random(); int time = (random.nextInt(10) + 1) * 1000; log.info("預(yù)計randomSpentTime方法執(zhí)行將耗時: " + 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ù)線程方式啟動 thread.setDaemon(true); return thread; }); TimeoutUtil timeoutUtil = new TimeoutUtil(executorService); for (int i = 1; i <= 10; i++) { log.info("\n=============第{}次超時測試=============", i); Thread.sleep(6000); long start = System.currentTimeMillis(); String result = timeoutUtil.doWithTimeLimit(() -> timeoutUtil.randomSpentTime(), 5000).getOrElse("默認(rèn)"); log.info("doWithTimeLimit方法實際耗時{}毫秒,結(jié)果:{}", System.currentTimeMillis() - start, result); } } }
以上是“Java如何編寫超時工具類”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)站標(biāo)題:Java如何編寫超時工具類
網(wǎng)頁鏈接:http://muchs.cn/article12/pipsdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、企業(yè)網(wǎng)站制作、虛擬主機(jī)、面包屑導(dǎo)航、做網(wǎng)站、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)