[英]Best practice when waiting for multiple threads - time, count or something else?
我的應用程序在運行時將包含多個獨立工作的線程(在本示例中為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方法。
我也是,
1)在第一個線程調用該方法后等待2秒,並假設所有線程現在也都到達了嗎? 要么
2)保持計數以確保所有活動線程都已到達? (如果線程在調用方法之前崩潰,則應用程序將等待永恆)
3)計數+超時?
4)???
這就是CyclicBarrier的用途。 它允許您定義線程將等待所有線程到達的位置,然后有選擇地運行Runnable
來執行同步或其他此類操作。
我認為您需要一個java.util.concurrent.CyclicBarrier。
后續問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.