gpt4 book ai didi

java - 阻塞代码在一个线程中执行

转载 作者:行者123 更新时间:2023-12-02 03:09:59 25 4
gpt4 key购买 nike

我创建了 WorkerExecutor 执行器并尝试执行 2 段长期代码。我的代码:

public class BVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
WorkerExecutor executor = vertx.createSharedWorkerExecutor("worker", 10, 10000);
executor.executeBlocking(future -> {
out.printf("start 1, %s \n", Thread.currentThread().getName());
try {
Thread.sleep(5_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
future.complete();
}, result -> {
out.printf("finish 2, %s \n", Thread.currentThread().getName());
});
executor.executeBlocking(future -> {
out.printf("start 2, %s \n", Thread.currentThread().getName());
try {
Thread.sleep(5_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
future.complete();
}, result -> {
out.printf("finish 2, %s \n", Thread.currentThread().getName());
});
}
}

执行后输出:

start 1, worker-0
start 2, worker-0
finish 2, vert.x-eventloop-thread-1
finish 2, vert.x-eventloop-thread-1

为什么阻塞代码只在一个线程中执行?

最佳答案

我在文档中找到了答案,我需要执行:

executeBlocking(Handler<Future<T>> blockingCodeHandler, boolean ordered, Handler<AsyncResult<T>> resultHandler)

ordered = false,否则我的代码将串行工作,而不是在同一上下文中并行工作

关于java - 阻塞代码在一个线程中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41196843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com