在Java中实现阻塞函数调用 [英] Implement a blocking function call in Java

查看:229
本文介绍了在Java中实现阻塞函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中实现阻塞函数调用的建议/最佳方法是什么,稍后可以通过另一个线程的调用解除阻塞?

What is the recommended / best way to implement a blocking function call in Java, that can be later unblocked by a call from another thread?

基本上我想对一个对象有两个方法,其中第一个调用阻塞任何调用线程,直到第二个方法由另一个线程运行:

Basically I want to have two methods on an object, where the first call blocks any calling thread until the second method is run by another thread:

public class Blocker {

  /* Any thread that calls this function will get blocked */
  public static SomeResultObject blockingCall() {
     // ...      
  }

  /* when this function is called all blocked threads will continue */
  public void unblockAll() {
     // ...
  }

} 

意图BTW不仅仅是为了获得阻塞行为,

The intention BTW is not just to get blocking behaviour, but to write a method that blocks until some future point when it is possible to compute the required result.

推荐答案

您可以使用 CountDownLatch

latch = new CountDownLatch(1);

要阻止,请调用:

latch.await();

要解除封锁,请致电:

latch.countDown();

这篇关于在Java中实现阻塞函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆