簡體   English   中英

為 java 中的方法創建超時的最佳方法是什么?

[英]what is the best way to create a timeout to a method in java?

我想在 x 秒后停止該方法。 我該怎么做?

編輯
我將詳細說明:我的 method() 要么是本機的,要么與其他服務器通信。
我不在循環中(因此我無法更改標志)如果存在,我將想要使用該方法的返回值。

這在很大程度上取決於您的方法在做什么。 最簡單的方法是定期檢查方法執行了多長時間,並在超出限制時返回。

long t0 = System.currentTimeMillis();
// do something
long t1 = System.currentTimeMillis();
if (t1-t0 > x*1000) {
    return;
}

如果要在單獨的線程中運行該方法,則可以執行以下操作:

public <T> T myMethod() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        try {
            T value = executor.invokeAny(Collections.singleton(new Callable<T>() {
                @Override
                public T call() throws Exception {
                    //your actual method code here
                    return null;
                }
            }), 3, TimeUnit.SECONDS);
            System.out.println("All went fine");
            return value;
        } catch (TimeoutException e) {
            System.out.println("Exceeded time limit, interrupted");
        } catch (Exception e) {
            System.out.println("Some error happened, handle it properly");
        }
        return null; /*some default value*/
    } finally {
        executor.shutdownNow();
    }
}

請注意,如果您在線程中執行一些不可中斷的 IO,則此方法將不起作用..

在我看來,最可靠的方法是多線程解決方案。 我將長時間運行的算法放在Runnable中,並使用ExecutorService以給定的超時時間執行線程。

此問題的答案提供了有關解決方案的更多詳細信息。

當然,現在該方法將與主線程並行執行,但您可以使用Thread#join強制執行單線程行為- 只需等待您的主線程,直到時間有限的工作線程完成或超過其超時限制。

這取決於你在做什么以及你需要有多准確。 如果您處於循環中,您可以使用 System.currentTimeMillis() 來跟蹤已經過去了多少時間。 只需獲取您開始的時間並定期檢查並查看已經過去了多長時間。

您可以生成一個新線程來開始處理,休眠 x 秒,然后做一些事情來停止處理線程。

您不能在單次執行中這樣做,您必須為此使用線程

我同意阿曼迪諾

看到這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM