亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

關(guān)于Java?中?Future?的?get?方法超時問題

 更新時間:2022年06月15日 08:56:53   作者:time-flies  
這篇文章主要介紹了Java?中?Future?的?get?方法超時,最常見的理解就是,“超時以后,當(dāng)前線程繼續(xù)執(zhí)行,線程池里的對應(yīng)線程中斷”,真的是這樣嗎?本文給大家詳細介紹,需要的朋友參考下吧

一、背景

很多 Java 工程師在準備面試時,會刷很多八股文,線程和線程池這一塊通常會準備線程的狀態(tài)、線程的創(chuàng)建方式,Executors 里面的一些工廠方法和為什么不推薦使用這些工廠方法,ThreadPoolExecutor 構(gòu)造方法的一些參數(shù)和執(zhí)行過程等。

工作中,很多人會使用線程池的 submit 方法 獲取 Future 類型的返回值,然后使用 java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) 實現(xiàn)“最多等多久”的效果。

但很多人對此的理解只停留在表面上,稍微問深一點點可能就懵逼了。

比如,java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) 超時之后,當(dāng)前線程會怎樣?線程池里執(zhí)行對應(yīng)任務(wù)的線程會有怎樣的表現(xiàn)?

如果你對這個問題沒有很大的把握,說明你掌握的還不夠扎實。

最常見的理解就是,“超時以后,當(dāng)前線程繼續(xù)執(zhí)行,線程池里的對應(yīng)線程中斷”,真的是這樣嗎?

二、模擬

2.1 常見寫法

下面給出一個簡單的模擬案例:

package basic.thread;
import java.util.concurrent.*;
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<?> future = executorService.submit(() -> {
            try {
                demo();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + "獲取的結(jié)果 -- start");
        Object result = future.get(100, TimeUnit.MILLISECONDS);
        System.out.println(threadName + "獲取的結(jié)果 -- end :" + result);
    }
    private static String demo() throws InterruptedException {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + ",執(zhí)行 demo -- start");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(threadName + ",執(zhí)行 demo -- end");
        return "test";
    }
}

輸出結(jié)果:

main獲取的結(jié)果 -- start
pool-1-thread-1,執(zhí)行 demo -- start
Exception in thread "main" java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at basic.thread.FutureDemo.main(FutureDemo.java:20)
pool-1-thread-1,執(zhí)行 demo -- end

我們可以發(fā)現(xiàn):當(dāng)前線程會因為收到 TimeoutException 而被中斷,線程池里對應(yīng)的線程“卻”繼續(xù)執(zhí)行完畢。

2.2 嘗試取消

我們嘗試對未完成的線程進行取消,發(fā)現(xiàn) Future#cancel 有個 boolean 類型的參數(shù)。

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

看源碼注釋我們可以知道:

當(dāng)設(shè)置為 true 時,正在執(zhí)行的任務(wù)將被中斷(interrupted);

當(dāng)設(shè)置為 false 時,如果任務(wù)正在執(zhí)行中,那么仍然允許任務(wù)執(zhí)行完成。

2.2.1 cancel(false)

此時,為了不讓主線程因為超時異常被中斷,我們 try-catch 包起來。

package basic.thread;
import org.junit.platform.commons.util.ExceptionUtils;
import java.util.concurrent.*;
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<?> future = executorService.submit(() -> {
            try {
                demo();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- start");
        try {
            Object result = future.get(100, TimeUnit.MILLISECONDS);
            System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- end :" + result);
        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果異常:" + ExceptionUtils.readStackTrace(e));
        }
        future.cancel(false);
        System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- cancel");
    }
    private static String demo() throws InterruptedException {
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo -- start");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo -- end");
        return "test";
    }
}

結(jié)果:

1653751759233,main獲取的結(jié)果 -- start
1653751759233,pool-1-thread-1,執(zhí)行 demo -- start
1653751759343,main獲取的結(jié)果異常:java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at basic.thread.FutureDemo.main(FutureDemo.java:23)

1653751759351,main獲取的結(jié)果 -- cancel
1653751760263,pool-1-thread-1,執(zhí)行 demo -- end

我們發(fā)現(xiàn),線程池里的對應(yīng)線程在 cancel(false) 時,如果已經(jīng)正在執(zhí)行,則會繼續(xù)執(zhí)行完成。

2.2.2 cancel(true)

package basic.thread;
import org.junit.platform.commons.util.ExceptionUtils;
import java.util.concurrent.*;
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<?> future = executorService.submit(() -> {
            try {
                demo();
            } catch (InterruptedException e) {
                System.out.println(System.currentTimeMillis() + "," + Thread.currentThread().getName() + ", Interrupted:" + ExceptionUtils.readStackTrace(e));
                throw new RuntimeException(e);
            }
        });
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- start");
        try {
            Object result = future.get(100, TimeUnit.MILLISECONDS);
            System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- end :" + result);
        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果異常:" + ExceptionUtils.readStackTrace(e));
        }
        future.cancel(true);
        System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- cancel");
    }
    private static String demo() throws InterruptedException {
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo -- start");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo -- end");
        return "test";
    }
}

執(zhí)行結(jié)果:

1653752011246,main獲取的結(jié)果 -- start
1653752011246,pool-1-thread-1,執(zhí)行 demo -- start
1653752011347,main獲取的結(jié)果異常:java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at basic.thread.FutureDemo.main(FutureDemo.java:24)

1653752011363,pool-1-thread-1, Interrupted:java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:340)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
    at basic.thread.FutureDemo.demo(FutureDemo.java:36)
    at basic.thread.FutureDemo.lambda$main$0(FutureDemo.java:14)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

1653752011366,main獲取的結(jié)果 -- cancel

可以看出,此時,如果目標線程未執(zhí)行完,那么會收到 InterruptedException ,被中斷。

當(dāng)然,如果此時不希望目標線程被中斷,可以使用 try-catch 包住,再執(zhí)行其他邏輯。

package basic.thread;
import org.junit.platform.commons.util.ExceptionUtils;
import java.util.concurrent.*;
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<?> future = executorService.submit(() -> {
            demo();
        });
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- start");
        try {
            Object result = future.get(100, TimeUnit.MILLISECONDS);
            System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- end :" + result);
        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果異常:" + ExceptionUtils.readStackTrace(e));
        }
        future.cancel(true);
        System.out.println(System.currentTimeMillis() + "," + threadName + "獲取的結(jié)果 -- cancel");
    }
    private static String demo() {
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo -- start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo 被中斷,自動降級");
        }
        System.out.println(System.currentTimeMillis() + "," + threadName + ",執(zhí)行 demo -- end");
        return "test";
    }
}

執(zhí)行結(jié)果:

1653752219803,main獲取的結(jié)果 -- start
1653752219803,pool-1-thread-1,執(zhí)行 demo -- start
1653752219908,main獲取的結(jié)果異常:java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at basic.thread.FutureDemo.main(FutureDemo.java:19)

1653752219913,main獲取的結(jié)果 -- cancel
1653752219914,pool-1-thread-1,執(zhí)行 demo 被中斷,自動降級
1653752219914,pool-1-thread-1,執(zhí)行 demo -- end

三、回歸源碼

我們直接看 java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) 的源碼注釋,就可以清楚地知道各種情況的表現(xiàn):

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

我們還可以選取幾個常見的實現(xiàn)類,查看下實現(xiàn)的基本思路:

java.util.concurrent.FutureTask#get(long, java.util.concurrent.TimeUnit)

   public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

java.util.concurrent.CompletableFuture#get(long, java.util.concurrent.TimeUnit)

    /**
     * Waits if necessary for at most the given time for this future
     * to complete, and then returns its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the result value
     * @throws CancellationException if this future was cancelled
     * @throws ExecutionException if this future completed exceptionally
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    public T get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        Object r;
        long nanos = unit.toNanos(timeout);
        return reportGet((r = result) == null ? timedGet(nanos) : r);
    }
  /**
     * Returns raw result after waiting, or null if interrupted, or
     * throws TimeoutException on timeout.
     */
    private Object timedGet(long nanos) throws TimeoutException {
        if (Thread.interrupted())
            return null;
        if (nanos <= 0L)
            throw new TimeoutException();
        long d = System.nanoTime() + nanos;
        Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
        boolean queued = false;
        Object r;
        // We intentionally don't spin here (as waitingGet does) because
        // the call to nanoTime() above acts much like a spin.
        while ((r = result) == null) {
            if (!queued)
                queued = tryPushStack(q);
            else if (q.interruptControl < 0 || q.nanos <= 0L) {
                q.thread = null;
                cleanStack();
                if (q.interruptControl < 0)
                    return null;
                throw new TimeoutException();
            }
            else if (q.thread != null && result == null) {
                try {
                    ForkJoinPool.managedBlock(q);
                } catch (InterruptedException ie) {
                    q.interruptControl = -1;
                }
            }
        }
        if (q.interruptControl < 0)
            r = null;
        q.thread = null;
        postComplete();
        return r;
    }

java.util.concurrent.Future#cancel 也一樣

/**
 * Attempts to cancel execution of this task.  This attempt will
 * fail if the task has already completed, has already been cancelled,
 * or could not be cancelled for some other reason. If successful,
 * and this task has not started when {@code cancel} is called,
 * this task should never run.  If the task has already started,
 * then the {@code mayInterruptIfRunning} parameter determines
 * whether the thread executing this task should be interrupted in
 * an attempt to stop the task.
 *
 * <p>After this method returns, subsequent calls to {@link #isDone} will
 * always return {@code true}.  Subsequent calls to {@link #isCancelled}
 * will always return {@code true} if this method returned {@code true}.
 *
 * @param mayInterruptIfRunning {@code true} if the thread executing this
 * task should be interrupted; otherwise, in-progress tasks are allowed
 * to complete
 * @return {@code false} if the task could not be cancelled,
 * typically because it has already completed normally;
 * {@code true} otherwise
 */
boolean cancel(boolean mayInterruptIfRunning);

java.util.concurrent.FutureTask#cancel

public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

可以看到 mayInterruptIfRunning 為 true 時,會執(zhí)行 Thread#interrupt 方法

java.util.concurrent.CompletableFuture#cancel

    /**
     * If not already completed, completes this CompletableFuture with
     * a {@link CancellationException}. Dependent CompletableFutures
     * that have not already completed will also complete
     * exceptionally, with a {@link CompletionException} caused by
     * this {@code CancellationException}.
     *
     * @param mayInterruptIfRunning this value has no effect in this
     * implementation because interrupts are not used to control
     * processing.
     *
     * @return {@code true} if this task is now cancelled
     */
    public boolean cancel(boolean mayInterruptIfRunning) {
        boolean cancelled = (result == null) &&
            internalComplete(new AltResult(new CancellationException()));
        postComplete();
        return cancelled || isCancelled();
    }

通過注釋我們也發(fā)現(xiàn),不同的實現(xiàn)類對參數(shù)的“效果”也有差異。

四、總結(jié)

我們學(xué)習(xí)時不應(yīng)該想當(dāng)然,不能紙上談兵,對于不太理解的地方,可以多看源碼注釋,多看源碼,多寫 DEMO 去模擬或調(diào)試。

到此這篇關(guān)于Java 中 Future 的 get 方法超時會怎樣的文章就介紹到這了,更多相關(guān)Java  Future 的 get 超時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java8快速實現(xiàn)List轉(zhuǎn)map 、分組、過濾等操作

    java8快速實現(xiàn)List轉(zhuǎn)map 、分組、過濾等操作

    這篇文章主要介紹了java8快速實現(xiàn)List轉(zhuǎn)map 、分組、過濾等操作,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • SpringBoot如何使用mica-xss防止Xss攻擊

    SpringBoot如何使用mica-xss防止Xss攻擊

    這篇文章主要介紹了SpringBoot如何使用mica-xss防止Xss攻擊問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Spring中的三級緩存與循環(huán)依賴詳解

    Spring中的三級緩存與循環(huán)依賴詳解

    Spring三級緩存是Spring框架中用于解決循環(huán)依賴問題的一種機制,這篇文章主要介紹了Spring三級緩存與循環(huán)依賴的相關(guān)知識,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2024-05-05
  • Java日常練習(xí)題,每天進步一點點(30)

    Java日常練習(xí)題,每天進步一點點(30)

    下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你
    2021-07-07
  • JavaSE一維數(shù)組和二維數(shù)組用法詳解

    JavaSE一維數(shù)組和二維數(shù)組用法詳解

    數(shù)組存儲同一種數(shù)據(jù)類型多個元素的集合,既可以存儲基本數(shù)據(jù)類型,也可以存儲引用數(shù)據(jù)類型,這篇文章主要給大家介紹了關(guān)于JavaSE一維數(shù)組和二維數(shù)組用法的相關(guān)資料,需要的朋友可以參考下
    2024-04-04
  • Java實現(xiàn)發(fā)送手機短信語音驗證功能代碼實例

    Java實現(xiàn)發(fā)送手機短信語音驗證功能代碼實例

    這篇文章主要介紹了Java實現(xiàn)發(fā)送手機短信語音驗證功能代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • Springboot WebJar打包及使用實現(xiàn)流程解析

    Springboot WebJar打包及使用實現(xiàn)流程解析

    這篇文章主要介紹了Springboot WebJar打包及使用實現(xiàn)流程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下的相關(guān)資料
    2020-08-08
  • SpringBoot集成Auth0 JWT的示例代碼

    SpringBoot集成Auth0 JWT的示例代碼

    本文主要介紹了SpringBoot集成Auth0 JWT的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Java動態(tài)編譯執(zhí)行代碼示例

    Java動態(tài)編譯執(zhí)行代碼示例

    這篇文章主要介紹了Java動態(tài)編譯執(zhí)行代碼示例,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • Maven基礎(chǔ)之如何修改本地倉庫的默認路徑

    Maven基礎(chǔ)之如何修改本地倉庫的默認路徑

    這篇文章主要介紹了Maven基礎(chǔ)之如何修改本地倉庫的默認路徑問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05

最新評論