亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Vertx:executeBlocking() 與 Future。有什么不同?

Vertx:executeBlocking() 與 Future。有什么不同?

慕娘9325324 2021-10-20 14:39:23
Vertx 文檔建議executeBlocking()在需要調用阻塞 API 時使用方法。另一方面,Vertx 還提供了一個 Future 的概念,它基本上做同樣的事情。但該executeBlocking()方法不是靜態的。它也不是 Future 的簡單包裝器,如果您查看它的實現,您會發現它非常復雜。這兩者有什么區別?假設我想以異步方式執行一些長時間運行的任務。這兩種方法有什么區別嗎?方法一:doTheJob() {    Future<Void> future = Future.future();    executeLongRunningBlockingOperation();    future.complete();    return future;}doTheJob().setHandler(asyncResult -> {    // ... handle result});方法二:vertx.executeBlocking(future -> {    executeLongRunningBlockingOperation();    future.complete();}, res -> {    // ... handle result});
查看完整描述

1 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

您的第一個示例不是Future. 調用executeLongRunningBlockingOperation()將阻塞主線程,直到該方法完成——也就是說,在阻塞操作完成之前不會發生任何其他事情。在您的第二個示例中,阻塞調用被分拆到后臺線程中,并且其他事情在它執行時繼續發生。


為了用更完整的示例說明這一點,此代碼:


public void executeLongRunningBlockingOperation() {

    Thread.sleep(5000);

}


public Future<Void> doTheJob() { 

    System.out.println("Doing the job...");

    Future<Void> future = Future.future();

    executeLongRunningBlockingOperation();

    // this line will not be called until executeLongRunningBlockingOperation returns!

    future.complete();

    // nor will this method! This means that the method won't return until the long operation is done!

    return future;

}


public static void main(String[] args) {

    doTheJob().setHandler(asyncResult -> {

        System.out.println("Finished the job");

    });

    System.out.println("Doing other stuff in the mean time...");

}

將產生以下輸出:


Doing the job...

Finished the job

Doing other stuff in the mean time...

而這段代碼(使用executeBlocking):


...

public Future<Void> doTheJob() { 

    System.out.println("Doing the job...");

    Future<Void> future = Future.future();

    Vertx vertx = Vertx.vertx();

    vertx.executeBlocking(call -> {

        executeLongRunningBlockingOperation();

        call.complete;

    }, result -> {

        // this will only be called once the blocking operation is done

        future.complete();

    });

    // this method returns immediately since we are not blocking the main thread

    return future;

}

...

將產生:


Doing the job...

Doing other stuff in the mean time...

Finished the job


查看完整回答
反對 回復 2021-10-20
  • 1 回答
  • 0 關注
  • 914 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號