首頁 Java java教程 怎麼使用Java編寫超時工具類

怎麼使用Java編寫超時工具類

May 04, 2023 pm 02:37 PM
java

1、說明

java已經為我們提供了解決方案。 jdk1.5帶來的並發庫Future類別可以滿足此需求。 Future類別中重要的方法有get()和cancel()。 get()取得資料對象,如果資料沒有加載,則在取得資料之前堵塞,cancel()取消資料加載。另一個get(timeout)操作表明,如果timeout時間內沒有得到,就會失敗回來,不會堵塞。

利用泛型和函數式介面編寫一個工具類,可以讓超時處理更方便,而不用到處寫程式碼。

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 业务函数
     * @param timeout     超时时间,ms
     * @return 返回值
     */
    public <R> Result<R> doWithTimeLimit(Supplier<R> bizSupplier, int timeout) {
        return doWithTimeLimit(bizSupplier, null, timeout);
    }
 
    /**
     * 有超时限制的方法
     *
     * @param bizSupplier   业务函数
     * @param defaultResult 默认值
     * @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执行超过%d毫秒,强制结束", timeout);
            log.error(errMsg, e);
            futureTask.cancel(true);
            result = defaultResult;
        }
        return of(result, errMsg);
    }
 
    /**
     * 随机耗时的测试方法
     */
    private String randomSpentTime() {
        Random random = new Random();
        int time = (random.nextInt(10) + 1) * 1000;
        log.info("预计randomSpentTime方法执行将耗时: " + 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);
                    // 以守护线程方式启动
                    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("默认");
            log.info("doWithTimeLimit方法实际耗时{}毫秒,结果:{}", System.currentTimeMillis() - start, result);
        }
    }
 
}
登入後複製

以上是怎麼使用Java編寫超時工具類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Java 中的平方根 Java 中的平方根 Aug 30, 2024 pm 04:26 PM

Java 中的平方根

Java 中的完美數 Java 中的完美數 Aug 30, 2024 pm 04:28 PM

Java 中的完美數

Java 中的隨機數產生器 Java 中的隨機數產生器 Aug 30, 2024 pm 04:27 PM

Java 中的隨機數產生器

Java中的Weka Java中的Weka Aug 30, 2024 pm 04:28 PM

Java中的Weka

Java 中的阿姆斯壯數 Java 中的阿姆斯壯數 Aug 30, 2024 pm 04:26 PM

Java 中的阿姆斯壯數

Java 中的史密斯數 Java 中的史密斯數 Aug 30, 2024 pm 04:28 PM

Java 中的史密斯數

Java Spring 面試題 Java Spring 面試題 Aug 30, 2024 pm 04:29 PM

Java Spring 面試題

突破或從Java 8流返回? 突破或從Java 8流返回? Feb 07, 2025 pm 12:09 PM

突破或從Java 8流返回?

See all articles