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

时间:2016-12-17 08:41:50

标签: java vert.x

我创建了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

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

1 个答案:

答案 0 :(得分:2)

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

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

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