gpt4 book ai didi

java - 等待多线程时的最佳实践 - 时间、计数或其他?

转载 作者:行者123 更新时间:2023-11-29 07:44:52 25 4
gpt4 key购买 nike

在运行时,我的应用程序将包含多个线程(在本示例中为 7)执行独立工作。然而,每隔一段时间,线程就必须同步它们的数据。

这将由线程调用它们都引用的 DataSynchronizer 对象来完成。

我对这门课的心流的想法是这样的:

public class DataSynchronizer {

public void synchronizeData(List<Data> threadData) {
// Wait for all 7 threads to call this method

// When all 7 are here, hold them here & do work using one of the threads
// or a new anonymous thread

// Release the threads & let them continue their independent work
}
}

我的问题是,在执行同步工作之前“等待所有 x 线程”的最佳方法是什么?

我知道所有线程都会在 1 秒内调用 synchronizeData 方法,彼此最多相隔 2 秒。

我也是,

1) 在第一个线程调用该方法后等待 2 秒,并假设所有线程现在也都已到达?或

2) 保持计数以确保所有 Activity 线程都已到达? (如果线程在调用方法之前崩溃,应用程序将永远等待)

3)计数+超时?

4) ???

最佳答案

这是一个CyclicBarrier是为了。它允许您定义线程等待所有线程到达的位置,然后可选择运行 Runnable 来执行同步或其他类似操作。

关于java - 等待多线程时的最佳实践 - 时间、计数或其他?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26712062/

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