我正在开发一个用例,如下所示。我是多线程新手,在使用它时遇到了这个问题。
- 我在网络上广播了一个 Activity 。
- 它被所有听众接收,他们向我单播了他们的信息。
- 这是在回调方法中接收的,如下所示,我将得到 N 个未知数量的回调线程。取决于特定时间的听众。
- 我必须收集所有订阅者的列表。
我必须等待至少 10 秒才能让所有订阅者回复我。
//Sender
public void sendMulticastEvent() {
api.sendEvent();
/* after sending event wait for 15 sec so call back can collect all the subscribers */
//start waiting now
}
//Callback method
public void receiveEventsCallback(final Event event) {
//i will receive multiple response threads here..
//event object will have the topic and subscribers details, which i will collect here
list.add(event)
notify()
//notify thread here so i have a cumulative list of all received events.
}
我只关心如何..?
- 在 sendMulticast 事件处开始等待 X 秒
- 将所有收到的事件添加到列表后,在 receiveEventsCallback() 处发出通知。
我已经从理论上阅读了等待和通知、倒计时闩锁和屏障。但我不确定哪个会好,因为我在多线程方面的经验很差。
最佳答案
- Start a wait at the sendMulticast event for X seconds
只需使用带有超时参数的 wait()
版本。
请注意,您应该在每次成功调用 wait()
后(即返回事件)手动更新超时值。
- Notify at receiveEventsCallback() after all the recieved events has been added to the list.
您的问题坚持认为您不知道您的网络中有多少听众。您怎么知道所有事件都已收到(并回复)?
发件人的唯一方法是等待 X 秒并处理在那一刻之前可用的所有回复。
关于java - 在 Java 线程中等待和通知给定的时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30711260/