這篇文章主要介紹Java如何編寫(xiě)超時(shí)工具類(lèi),文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
我們提供的服務(wù)有:網(wǎng)站建設(shè)、成都網(wǎng)站制作、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、江山ssl等。為上千多家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢(xún)和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的江山網(wǎng)站制作公司
1. 簡(jiǎn)單,只需理解基本的概念,就可以編寫(xiě)適合于各種情況的應(yīng)用程序;2. 面向?qū)ο螅?. 分布性,Java是面向網(wǎng)絡(luò)的語(yǔ)言;4. 魯棒性,java提供自動(dòng)垃圾收集來(lái)進(jìn)行內(nèi)存管理,防止程序員在管理內(nèi)存時(shí)容易產(chǎn)生的錯(cuò)誤。;5. 安全性,用于網(wǎng)絡(luò)、分布環(huán)境下的Java必須防止病毒的入侵。6. 體系結(jié)構(gòu)中立,只要安裝了Java運(yùn)行時(shí)系統(tǒng),就可在任意處理器上運(yùn)行。7. 可移植性,Java可以方便地移植到網(wǎng)絡(luò)上的不同機(jī)器。8.解釋執(zhí)行,Java解釋器直接對(duì)Java字節(jié)碼進(jìn)行解釋執(zhí)行。
1、說(shuō)明
java已經(jīng)為我們提供了解決辦法。jdk1.5帶來(lái)的并發(fā)庫(kù)Future類(lèi)可以滿(mǎn)足這一需求。Future類(lèi)中重要的方法有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ù)式接口編寫(xiě)一個(gè)工具類(lèi),可以讓超時(shí)處理更方便,而不用到處寫(xiě)代碼。
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ù)線(xiàn)程方式啟動(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); } } }
以上是“Java如何編寫(xiě)超時(shí)工具類(lèi)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)站標(biāo)題:Java如何編寫(xiě)超時(shí)工具類(lèi)
網(wǎng)頁(yè)鏈接:http://chinadenli.net/article12/pipsdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營(yíng)銷(xiāo)推廣、企業(yè)網(wǎng)站制作、虛擬主機(jī)、面包屑導(dǎo)航、做網(wǎng)站、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)