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
添加回答
舉報