简体   繁体   English

如何使用 CountDownLatch 从 Callable 返回值?

[英]How to return value from Callable with CountDownLatch?

I want to use CountDownLatch with Callabe interface.我想将CountDownLatchCallabe接口一起使用。 I have Person class implements Callable interface which has CountDownLatch and Integer , Person#call() method returns integer value and within finally block countDown() method called.我有Person class 实现了具有CountDownLatchIntegerCallable接口, Person#call()方法返回 integer 值并在 finally 块内调用countDown()方法。 2 Threads created by Executors.newFixedThreadPool(2) and submitted Person objects within Main class .I want to know this implementation is ok? 2 由Executors.newFixedThreadPool(2)创建并在Main class中提交Person对象的线程。我想知道这个实现是否可以?

public class Person implements Callable<Integer> {
    private final CountDownLatch countDownLatch;
    private final Integer count;

    public Person(CountDownLatch countDownLatch, Integer count) {
        this.countDownLatch = countDownLatch;
        this.count = count;
    }

    @Override
    public Integer call() throws Exception {
        try {
            return count;
        } finally {
            countDownLatch.countDown();
        }
    }
}
public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<Integer> future1 = executorService.submit(new Person(countDownLatch, 5));
        Future<Integer> future2 = executorService.submit(new Person(countDownLatch, 4));
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(future1.get() + future2.get());
    }
}

I want to know this implementation is ok?我想知道这个实现可以吗?

That totally depends on what you are trying to achieve with this code.这完全取决于您要使用此代码实现的目标。 As is, your code is simply adding 5 and 4 together and printing the result of 9 to the console.实际上,您的代码只是将 5 和 4 相加并将 9 的结果打印到控制台。 You could simply do that with:你可以简单地做到这一点:

System.out.println(5+4);

If the point of your code is to use a CountDownLatch effectively, then yes you are using it correctly to detect that the Call() method has been invoked on both Person objects in an asynchronous manner before continuing the main method/thread.如果您的代码的目的是有效地使用 CountDownLatch,那么是的,您正在正确地使用它来检测在继续主方法/线程之前以异步方式在两个 Person 对象上调用了 Call() 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM