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
添加回答
举报