我使用 CountDownLatch 等待来自另一个组件(在不同线程中运行)的特定事件。以下方法符合我的软件的语义,但我不确定它是否按我预期的那样工作:
mCountDownLatch.await(3000, TimeUnit.MILLISECONDS)
otherComponent.aStaticVolatileVariable = true;
mCountDownLatch.await(3500, TimeUnit.MILLISECONDS);
... <proceed with other stuff>
场景应该是这样的:我等了 3 秒,如果 latch 没有倒数到 0,我就用那个变量通知其他组件,然后我最多等 3.5 秒。如果再次超时,那我就不管了,继续进行其他操作。
注意:我知道它看起来不像那样,但上面的场景在我的软件中是完全合理和有效的。
我确实阅读了 await(int,TimeUnit) 和 CountDownLatch 的文档,但我不是 Java/Android 专家,所以我需要确认。对我来说,所有场景看起来都有效:
我是否正确使用 await(...)?即使同一对象上的前一个 await(...) 超时,是否可以按上述方式使用第二个 await(...)?
最佳答案
如果我正确理解你的问题,这个测试证明你所有的假设/要求都是真实的/满足的。 (使用 JUnit 和 Hamcrest 运行。)请注意 runCodeUnderTest() 方法中的代码,尽管它穿插着时间记录并且超时减少了 10 倍。
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
public class CountdownLatchTest {
static volatile boolean signal;
CountDownLatch latch = new CountDownLatch(1);
long elapsedTime;
long[] wakeupTimes = new long[2];
@Before
public void setUp() throws Exception {
signal = false;
}
@Test
public void successfulCountDownDuringFirstAwait() throws Exception {
countDownAfter(150);
runCodeUnderTest();
assertThat((double) elapsedTime, closeTo(150, 10));
assertThat(wakeupTimeSeparation(), lessThan(10));
}
@Test
public void successfulCountDownDuringSecondAwait() throws Exception {
countDownAfter(450);
runCodeUnderTest();
assertThat((double) elapsedTime, closeTo(450, 10));
assertThat((double) wakeupTimeSeparation(), closeTo(150, 10));
}
@Test
public void neverCountDown() throws Exception {
runCodeUnderTest();
assertThat((double) elapsedTime, closeTo(650, 10));
assertThat((double) wakeupTimeSeparation(), closeTo(350, 10));
}
@Test
public void countDownAfterSecondTimeout() throws Exception {
countDownAfter(1000);
runCodeUnderTest();
assertThat((double) elapsedTime, closeTo(650, 10));
assertThat((double) wakeupTimeSeparation(), closeTo(350, 10));
}
@Test
public void successfulCountDownFromSignalField() throws Exception {
countDownAfterSignal();
runCodeUnderTest();
assertThat((double) elapsedTime, closeTo(300, 10));
}
private int wakeupTimeSeparation() {
return (int) (wakeupTimes[1] - wakeupTimes[0]);
}
private void runCodeUnderTest() throws InterruptedException {
long start = System.currentTimeMillis();
latch.await(300, TimeUnit.MILLISECONDS);
wakeupTimes[0] = System.currentTimeMillis();
signal = true;
latch.await(350, TimeUnit.MILLISECONDS);
wakeupTimes[1] = System.currentTimeMillis();
elapsedTime = wakeupTimes[1] - start;
}
private void countDownAfter(final long millis) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
sleep(millis);
latch.countDown();
}
}).start();
}
private void countDownAfterSignal() {
new Thread(new Runnable() {
@Override
public void run() {
boolean trying = true;
while (trying) {
if (signal) {
latch.countDown();
trying = false;
}
sleep(5);
}
}
}).start();
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new IllegalStateException("Unexpected interrupt", e);
}
}
}
关于java - 多次调用 CountDownLatch.await(int) 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10770419/
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht