最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java多線(xiàn)程Thread , Future , Callable , FutureTask的使用

 更新時(shí)間:2024年04月30日 09:41:33   作者:perfecto1  
本文主要介紹了Java多線(xiàn)程Thread , Future , Callable , FutureTask的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

 Thread創(chuàng)建一個(gè)線(xiàn)程

在想要使用多線(xiàn)程的技術(shù)來(lái)進(jìn)行相應(yīng)的操作的時(shí)候: 可以含有以下的方向來(lái)進(jìn)行設(shè)計(jì)思考! 在創(chuàng)建一個(gè)線(xiàn)程的時(shí)候通常是創(chuàng)建一個(gè)Thread的。 但是這個(gè)Thread,是含有多種方式來(lái)進(jìn)行創(chuàng)建操作的。 例如: 直接使用空參數(shù)的構(gòu)造器進(jìn)行創(chuàng)建操作:

        System.out.println("start:" + System.currentTimeMillis());
        Thread thread = new Thread();
        thread.start();
        System.out.println("end:" + System.currentTimeMillis());

這樣執(zhí)行是沒(méi)有什么效果的。這種情況就是你啟動(dòng)了一個(gè)線(xiàn)程,但是這個(gè)線(xiàn)程是沒(méi)有任何事情要干的。

時(shí)間是過(guò)的飛起的。

但是還有一種方法也是可以進(jìn)行線(xiàn)程的啟動(dòng)操作的。

使用含有參數(shù)方法的構(gòu)造器進(jìn)行創(chuàng)建線(xiàn)程:

System.out.println(Thread.currentThread() + "----start:" + System.currentTimeMillis());
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我正在執(zhí)行一個(gè)任務(wù),不要打擾我!");
        System.out.println(Thread.currentThread());
    }
});
thread.start();
System.out.println(Thread.currentThread() + "----end:" + System.currentTimeMillis());

這種是開(kāi)啟一個(gè)線(xiàn)程讓其來(lái)進(jìn)行線(xiàn)程任務(wù)的執(zhí)行操作的。

但是你有沒(méi)有發(fā)現(xiàn),這種方式有一點(diǎn)缺點(diǎn)的。

這個(gè)開(kāi)啟的線(xiàn)程是相當(dāng)于我要讓其進(jìn)行一些子任務(wù)的執(zhí)行操作的。

Thread進(jìn)行異步處理

類(lèi)似于我是老師,我想讓學(xué)習(xí)委員去辦公室?guī)臀夷靡恍?shū)來(lái)的。此時(shí)學(xué)習(xí)委員已經(jīng)出發(fā)了,但是我想起來(lái)我好像是帶了書(shū)的。我想要讓學(xué)習(xí)委員不要去辦公室拿書(shū)了。

若我直接采用這種方式來(lái)來(lái)進(jìn)行執(zhí)行操作的話(huà),是無(wú)法滿(mǎn)足我的需求的。只要是我叫他去拿書(shū)了,她就會(huì)喊不回來(lái)的。

那是否能對(duì)這種方式進(jìn)行相應(yīng)的改造操作呢???

java的開(kāi)發(fā)者是給了我們一種實(shí)現(xiàn)的方式的。

使用Future的接口滿(mǎn)足需求。

相應(yīng)的解釋?zhuān)?/p>

A Future 表示異步計(jì)算的結(jié)果。提供了用于檢查計(jì)算是否完成、等待計(jì)算完成以及檢索計(jì)算結(jié)果的方法。只有在計(jì)算完成后才能使用方法 get 檢索結(jié)果,必要時(shí)會(huì)阻止,直到它準(zhǔn)備就緒。取消是通過(guò)該 cancel 方法執(zhí)行的。提供了其他方法來(lái)確定任務(wù)是正常完成還是已取消。計(jì)算完成后,無(wú)法取消計(jì)算。如果為了可取消性而使用 a Future ,但不提供可用的結(jié)果,則可以聲明表單 Future<?> 的類(lèi)型,并作為基礎(chǔ)任務(wù)的結(jié)果返回 null 。

public interface Future<V> {
?
    /**
     * 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);
?
    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();
?
    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();
?
    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @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
     */
    V get() throws InterruptedException, ExecutionException;
?
    /**
     * 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;
}

通過(guò)這個(gè)接口就可以實(shí)現(xiàn)相對(duì)應(yīng)的功能操作了。

給予了一個(gè)接口想要將其進(jìn)行實(shí)現(xiàn)操作就得要相關(guān)的實(shí)現(xiàn)類(lèi)。

登場(chǎng)的就是FutureTask的類(lèi)進(jìn)行操作的。

public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;       // ensure visibility of callable
}

執(zhí)行一下相關(guān)的代碼:

 FutureTask<String> stringFutureTask = new FutureTask<String>(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我正在執(zhí)行一個(gè)任務(wù),不要打擾我!");
                System.out.println(Thread.currentThread());
            }
        } , null);
?
        Thread futureThread = new Thread(stringFutureTask);
        futureThread.start();
//      是可以滿(mǎn)足對(duì)一個(gè)進(jìn)行任務(wù)的取消工作的
//        stringFutureTask.cancel(true);
        System.out.println(stringFutureTask.isCancelled());
?
?
        Thread futureThread1 = new Thread(stringFutureTask);
        futureThread1.start();

第二個(gè) futureThread1 是不會(huì)執(zhí)行的。

解釋原因:

在Java中,FutureTask只能執(zhí)行一次。當(dāng)您嘗試第二次執(zhí)行相同的FutureTask實(shí)例時(shí),它不會(huì)執(zhí)行任何操作。這是因?yàn)?code>FutureTask的狀態(tài)在第一次執(zhí)行后會(huì)改變,它不會(huì)重新開(kāi)始。如果第一個(gè)線(xiàn)程(futureThread)已經(jīng)開(kāi)始執(zhí)行stringFutureTask,那么第二個(gè)線(xiàn)程(futureThread1)嘗試開(kāi)始相同的stringFutureTask時(shí),將不會(huì)有任何效果,因?yàn)?code>FutureTask的狀態(tài)已經(jīng)不是初始狀態(tài)了。

這里是一些關(guān)鍵點(diǎn):

  • FutureTask在執(zhí)行后會(huì)進(jìn)入完成狀態(tài)。

  • 如果嘗試再次執(zhí)行一個(gè)已經(jīng)完成的FutureTask,它不會(huì)重新執(zhí)行。

  • 如果需要重新執(zhí)行任務(wù),您需要?jiǎng)?chuàng)建一個(gè)新的FutureTask實(shí)例。

上面相關(guān)的例子,已經(jīng)將一個(gè)老師叫學(xué)習(xí)委員去辦公室拿書(shū)的例子叫停了。也就是說(shuō)現(xiàn)在是實(shí)現(xiàn)了異步處理的操作。

帶有參數(shù)的返回線(xiàn)程處理

我現(xiàn)在還有一個(gè)需求,是干嘛的呢???我不是喊學(xué)習(xí)委員去辦公室拿書(shū)了嗎??我想要那個(gè)他拿到的書(shū)給我手上。這個(gè)功能是怎么實(shí)現(xiàn)的呢?

也就是含有返回值的相關(guān)的例子?。。?/p>

JUC給了一個(gè)方法,是可以直接將一個(gè)Callable的接口傳過(guò)來(lái)的

public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}

使用這個(gè)接口作為參數(shù)傳給的FutureTask進(jìn)行任務(wù)的初始化操作。

我們知道Callable接口是有返回值的。那么就可以類(lèi)似于得到相應(yīng)的那一本書(shū)了!?。?/p>

操作實(shí)現(xiàn):

    FutureTask<String> stringFutureTask = new FutureTask<String>(new Callable<String>() {
        @Override
        public String call() throws Exception {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我正在執(zhí)行一個(gè)任務(wù),不要打擾我!");
            return "老師,我拿到書(shū)了";
        }
    });
?
    Thread thread = new Thread(stringFutureTask);
    thread.start();
    System.out.println(stringFutureTask.get());

將得到的東西進(jìn)行返回操作。這樣的話(huà)就可以實(shí)現(xiàn)三種基本的功能操作了。

到此這篇關(guān)于Java多線(xiàn)程Thread , Future , Callable , FutureTask的使用的文章就介紹到這了,更多相關(guān)Java Thread , Future , Callable , FutureTask內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot集成本地緩存Caffeine的三種使用方式(小結(jié))

    springboot集成本地緩存Caffeine的三種使用方式(小結(jié))

    本文主要介紹了springboot集成本地緩存Caffeine的三種使用方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • java接口私有方法實(shí)現(xiàn)過(guò)程解析

    java接口私有方法實(shí)現(xiàn)過(guò)程解析

    這篇文章主要介紹了java接口私有方法實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • SpringBoot定時(shí)任務(wù)兩種(Spring Schedule 與 Quartz 整合 )實(shí)現(xiàn)方法

    SpringBoot定時(shí)任務(wù)兩種(Spring Schedule 與 Quartz 整合 )實(shí)現(xiàn)方法

    本篇文章主要介紹了SpringBoot定時(shí)任務(wù)兩種(Spring Schedule 與 Quartz 整合 )實(shí)現(xiàn)方法,詳細(xì)的介紹了Spring Schedule 與 Quartz 整合的兩種方法,有興趣的可以了解一下。
    2017-03-03
  • Java實(shí)現(xiàn)雙保險(xiǎn)線(xiàn)程的示例代碼

    Java實(shí)現(xiàn)雙保險(xiǎn)線(xiàn)程的示例代碼

    這篇文章主要介紹了Java實(shí)現(xiàn)雙保險(xiǎn)線(xiàn)程的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • Java 面試題基礎(chǔ)知識(shí)集錦

    Java 面試題基礎(chǔ)知識(shí)集錦

    本文主要介紹Java基礎(chǔ)面試題集錦,這里整理了面試java工程師的基礎(chǔ)知識(shí)題錦,有需要的小伙伴可以參考下
    2016-09-09
  • Java中的Timer與TimerTask原理詳解

    Java中的Timer與TimerTask原理詳解

    這篇文章主要介紹了Java中的Timer與TimerTask原理詳解,timerTask本身沒(méi)什么意義,只是和timer集合操作的一個(gè)對(duì)象,實(shí)現(xiàn)它就必然有對(duì)應(yīng)的run方法,以被調(diào)用,他甚至于根本不需要實(shí)現(xiàn)Runnable,需要的朋友可以參考下
    2023-07-07
  • java多線(xiàn)程使用mdc追蹤日志方式

    java多線(xiàn)程使用mdc追蹤日志方式

    這篇文章主要介紹了java多線(xiàn)程使用mdc追蹤日志方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 使用Spring AOP實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)讀寫(xiě)分離案例分析(附demo)

    使用Spring AOP實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)讀寫(xiě)分離案例分析(附demo)

    分布式環(huán)境下數(shù)據(jù)庫(kù)的讀寫(xiě)分離策略是解決數(shù)據(jù)庫(kù)讀寫(xiě)性能瓶頸的一個(gè)關(guān)鍵解決方案,這篇文章主要介紹了使用Spring AOP實(shí)現(xiàn)MySQL數(shù)據(jù)庫(kù)讀寫(xiě)分離案例分析(附demo),有興趣的可以了解一下。
    2017-01-01
  • Java selenium上傳文件的實(shí)現(xiàn)

    Java selenium上傳文件的實(shí)現(xiàn)

    本文主要介紹了Java selenium上傳文件的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Java 根據(jù)某個(gè) key 加鎖的實(shí)現(xiàn)方式

    Java 根據(jù)某個(gè) key 加鎖的實(shí)現(xiàn)方式

    日常開(kāi)發(fā)中,有時(shí)候需要根據(jù)某個(gè) key 加鎖,確保多線(xiàn)程情況下,對(duì)該 key 的加鎖和解鎖之間的代碼串行執(zhí)行,這篇文章主要介紹了Java 根據(jù)某個(gè) key 加鎖的實(shí)現(xiàn)方式,需要的朋友可以參考下
    2023-03-03

最新評(píng)論

合山市| 盐池县| 淮滨县| 怀仁县| 乐安县| 朔州市| 耒阳市| 英超| 青阳县| 广宁县| 南雄市| 军事| 肇源县| 板桥市| 永春县| 荆门市| 拉萨市| 佳木斯市| 梅州市| 新乡县| 陆丰市| 弋阳县| 北安市| 洪泽县| 平和县| 通辽市| 河曲县| 山丹县| 许昌县| 江都市| 海晏县| 平安县| 和平县| 尤溪县| 宁蒗| 东乡族自治县| 博野县| 慈利县| 安新县| 江西省| 金塔县|