gpt4 book ai didi

java - 安卓。 Countdownlatch.await 不起作用

转载 作者:行者123 更新时间:2023-11-29 05:22:21 26 4
gpt4 key购买 nike

我不知道我在这里做错了什么。 Countdownlatch.await 不起作用。绝对没有等待时间。我用荒谬的数字(50 秒)进行了测试,并立即收到了调用后记。我正在尝试在 UI 线程上使用它。我还有另一个线程在运行。

代码:

private final CountDownLatch latch = new CountDownLatch(1); //called earlier

void someMethod() {
//code
Runnable flashScreen = new Runnable() {
@Override
public void run() {
flashScreen();
}
};

runOnUiThread(flashScreen);
//Mode code
}

private void flashScreen()
{
final TextView monthDayYear = (TextView)findViewById(R.id.month_day_year);
final TextView hourMinuteSecond = (TextView)findViewById(R.id.hour_minute_second);
//Get date and time
final SyncModule syncModule = _application.getSyncModule();
syncModule.start();

while(counter.intValue() < 150) {
try {
//Thread.sleep(10);
latch.countDown();
latch.await(10, TimeUnit.MILLISECONDS);
counter.incrementAndGet();
} catch (InterruptedException ex) {
Util.appendLog("SyncActivity: InterruptedException while flashing camera " + ex.getMessage());
}
}

final ImageView fadeView = (ImageView)findViewById(R.id.sync_flash_rectangle);
fadeView.setBackgroundColor(Color.WHITE);
fadeIn(fadeView, 1, 0, 1000, true);

Calendar syncTime = syncModule.getDateAndTime();

monthDayYear.setText(new SimpleDateFormat("MM/dd/yyyy").format(syncTime.getTime()));
hourMinuteSecond.setText(new SimpleDateFormat("HH:mm:ss:00").format(syncTime.getTime()));

try {
latch.countDown();
latch.await(50, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Util.appendLog("SyncActivity: InterruptedException while flashing camera " + ex.getMessage());
}

counter.set(1000);

}

最佳答案

我不确定您是否了解 CountDownLatch 的工作原理。 countDown() 方法和await() 方法一般在不同的线程中调用。

来自 CountDownLatch 的 Java8 JavaDoc :

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

在您当前的代码中,您的闩锁倒计时为 1(从示例的第一行 new CountDownLatch(1);)。在您调用 await() 的两个位置,您紧接在调用 countDown() 之前,这会导致您的闩锁倒计时达到 0(或什至更少) .因此,任何对 await() 的调用都不会阻塞,因为倒计时已经到了。

我不是很清楚你想要完成什么,但如果你提供更多细节,我可能会提供进一步的建议。

关于java - 安卓。 Countdownlatch.await 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24170595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com