[英]Wait and Notify in Java threads for a given interval
i am working on a usecase as below. 我正在使用以下用例。 I am new to multi threading and facing this issue with using it.
我是多线程的新手,使用它时遇到了这个问题。
I have to wait at least 10sec for all the subscribers to reply to me. 我必须至少等待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.
}
I am only concerned on How to.. ? 我只关心如何。
I have read theroitically on wait and notify, Countdownlatch and Barrier. 我已经阅读了有关等待和通知的理论文章,Countdownlatch和Barrier。 But i am not sure which would be good, because of my poor experience in multithreading.
但是由于我在多线程方面的经验不足,我不确定哪种方法会好。
If you know how many replies you will get - assuming each response will trigger the creation of a new thread - use a CyclicBarrier. 如果您知道将收到多少答复(假设每个答复都会触发创建新线程),请使用CyclicBarrier。
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html
example: 例:
CyclicBarrier barrier = new CyclicBarrier(3);
Runnable thread = new Runnable()
{
@Override
public void run()
{
try
{
barrier.await();
for (int i = 0; i < 10; i++)
{
System.out.printf("%d%n", i);
}
}
catch (InterruptedException | BrokenBarrierException ex)
{
ex.printStackTrace();
// handle the exception properly in real code.
}
}
};
Untill the third barrier.await() each thread will wait. 在第三个barrier.await()之前,每个线程将等待。
- Start a wait at the sendMulticast event for X seconds
在sendMulticast事件上等待X秒
Just use version of wait()
which takes timeout argument. 只需使用带有超时参数的
wait()
版本。
Note, that you should manually update timeout value after every successfull wait()
call (that is, which return event). 请注意,您应该在每次成功的
wait()
调用(即返回事件)之后手动更新超时值。
- Notify at receiveEventsCallback() after all the recieved events has been added to the list.
将所有收到的事件添加到列表后,在receiveEventsCallback()处进行通知。
Your question insists that you don't know, how many listeners in your network. 您的问题是您不知道网络中有多少听众。 How can you know, that all of them have event recieved (and replied)?
您怎么知道他们都收到(并回复)了事件?
The only way for sender is to wait X second and process all replies available till that moment. 发件人的唯一方法是等待X秒,然后处理所有可用的回复,直到那一刻。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.