睡觉并检查,直到情况成立

编程入门 行业动态 更新时间:2024-10-24 10:25:56
本文介绍了睡觉并检查,直到情况成立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Java中是否有一个库可以执行以下操作?一个线程应该重复 sleep x毫秒,直到条件变为真或达到最大时间。

Is there a library in Java that does the following? A thread should repeatedly sleep for x milliseconds until a condition becomes true or the max time is reached.

这种情况主要发生在测试等待某些条件变为真时。条件受另一个线程的影响。

This situation mostly occurs when a test waits for some condition to become true. The condition is influenced by another thread.

为了让它更清晰,我希望测试到在失败之前只等待X ms。它不能永远等待条件成为现实。我正在添加一个人为的例子。

Just to make it clearer, I want the test to wait for only X ms before it fails. It cannot wait forever for a condition to become true. I am adding a contrived example.

class StateHolder{ boolean active = false; StateHolder(){ new Thread(new Runnable(){ public void run(){ active = true; } }, "State-Changer").start() } boolean isActive(){ return active; } } class StateHolderTest{ @Test public void shouldTurnActive(){ StateHolder holder = new StateHolder(); assertTrue(holder.isActive); // i want this call not to fail } }

推荐答案

编辑

大多数答案都集中在低级API上,包括等待和通知或条件(更多或更多或不一样的方式):当你不习惯它时,很难做到正确。证明:其中2个答案没有正确使用等待。 java.util.concurrent 为您提供了一个高级API,其中隐藏了所有这些错综复杂的内容。

Most answers focus on the low level API with waits and notifies or Conditions (which work more or less the same way): it is difficult to get right when you are not used to it. Proof: 2 of these answers don't use wait correctly. java.util.concurrent offers you a high level API where all those intricacies have been hidden.

恕我直言,当并发包中有一个内置类实现相同的功能时,没有必要使用等待/通知模式。

IMHO, there is no point using a wait/notify pattern when there is a built-in class in the concurrent package that achieves the same.

A CountDownLatch 就是这样:

  • 当条件成立时,在等待的线程中调用 latch.countdown();
  • ,使用: boolean ok = latch.await (1,TimeUnit.SECONDS);
  • When the condition becomes true, call latch.countdown();
  • in your waiting thread, use : boolean ok = latch.await(1, TimeUnit.SECONDS);

Contrived example:

Contrived example:

final CountDownLatch done = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { longProcessing(); done.countDown(); } }).start(); //in your waiting thread: boolean processingCompleteWithin1Second = done.await(1, TimeUnit.SECONDS);

注意:CountDownLatches是线程安全的。

Note: CountDownLatches are thread safe.

更多推荐

睡觉并检查,直到情况成立

本文发布于:2023-11-12 01:41:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580151.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!