runnableFuture设置结果

时间:2017-04-05 14:25:15

标签: java concurrency future

我想做这样的事情:

在thread1中

Future<String> future = socketService.registerRequest(uuid);
System.out.println(future.get()); // I want to be blocked here while I will not signal from another thread

registerRequest:

public Future<String> registerRequest(String uuid) {
    RunnableFuture<String> runnableFuture = new FutureTask<String>(); // this code doesn't compile because it there is no default constructor 
    results.put(uuid, runnableFuture);
    return runnableFuture;
}

另一个帖子中,我想像这样说

results.get(uuid).setResult("It is result from another thread")

如何在java中实现它?

3 个答案:

答案 0 :(得分:0)

如果我理解正确你想要在一个线程中被阻止,直到不同的线程产生一些结果。我认为BlockingQueue是一个很好的解决方案,这里是与例子blocking queue example的链接

答案 1 :(得分:0)

您可以使用ExecutorService

这样做
private ExecutorService executorService = Executors.newFixedThreadPool(4);

public Future<String> registerRequest(String uuid) {
    RunnableFuture<String> runnableFuture = new FutureTask<String>(

    Future<String> future = executorService.submit(() -> {
         return "It is result from another thread";
    });

    // I left out the UUID part, please add yourself.

    return future;
}

答案 2 :(得分:0)

您可能只想在submit上致电ExecutorService并保持良好状态,例如。

ExecutorService yourExecutorService = /* e.g. */ Executors.newCachedThreadPool();
Future<String> future = yourExecutorService.submit(() -> "i am the answer created on another thread");

// the following line blocks, until the value is available:
System.out.println(future.get());

您可能还想查看Executors javadoc并按照那里的文档进行操作。

关于FutureTask:它只是一个包装器,提供了两个构造函数,一个accepting a Callable和一个Runnable。但你可能甚至不需要如前所示的这种包装。