【问题标题】:Sync version of async methodasync 方法的同步版本
【发布时间】:2011-06-06 02:34:18
【问题描述】:

在 Java 中创建异步方法的同步版本的最佳方法是什么?

假设你有一个包含这两种方法的类:

asyncDoSomething(); // Starts an asynchronous task
onFinishDoSomething(); // Called when the task is finished 

您将如何实现在任务完成之前不会返回的同步doSomething()

【问题讨论】:

    标签: java asynchronous synchronous


    【解决方案1】:

    看看CountDownLatch。您可以通过以下方式模拟所需的同步行为:

    private CountDownLatch doneSignal = new CountDownLatch(1);
    
    void main() throws InterruptedException{
      asyncDoSomething();
      //wait until doneSignal.countDown() is called
      doneSignal.await();
    }
    
    void onFinishDoSomething(){
      //do something ...
      //then signal the end of work
      doneSignal.countDown();
    }
    

    您也可以使用CyclicBarrier 与这样的 2 方实现相同的行为:

    private CyclicBarrier barrier = new CyclicBarrier(2);
    
    void main() throws InterruptedException{
      asyncDoSomething();
      //wait until other party calls barrier.await()
      barrier.await();
    }
    
    void onFinishDoSomething() throws InterruptedException{
      //do something ...
      //then signal the end of work
      barrier.await();
    }
    

    但是,如果您可以控制 asyncDoSomething() 的源代码,我建议您重新设计它以返回 Future<Void> 对象。通过这样做,您可以在需要时轻松地在异步/同步行为之间切换,如下所示:

    void asynchronousMain(){
      asyncDoSomethig(); //ignore the return result
    }
    
    void synchronousMain() throws Exception{
      Future<Void> f = asyncDoSomething();
      //wait synchronously for result
      f.get();
    }
    

    【讨论】:

    • 我希望我能给你超过 1 票。 Future的优秀推荐
    • @rodion 如果我在循环中使用 CountDownLatch 并在循环中对其进行实例化,它会停止循环执行下一次迭代,直到迭代的任务完成还是继续迭代?如果我的问题不清楚,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多