I have the following problem. Given a Interface EventNotifier for the Observer Pattern:
public interface EventNotifier {
void newEvent(final String value);
}
A class, which implements this Interface, can register at another class, which calls very often the method newEvent. The Interface is given by a external library, so I cannot change it. Up to now I implemented it with an anonymous class:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
watcher = new Watcher(new EventNotifier() {
@Override
public void newEvent(String value) {
//do some stuff
//will be called more than 20 times per second
}
});
});
t.start();
For better code readability I would like to expose this anonymous class into a new class, which extends Thread (because the handling should be parallel to other things).
How can I write a Thread, which does nothing (no endless-loop etc.), but wait for calling the newEvent method? The problem is, that newEvent will be called more than 20 times a second, so I cannot start a new thread for each call but the whole thing should be in a thread.
I hope you get the problem and somebody can help me.
What makes your post confusing is that the EventNotifier
is in fact an observer/listener (it receives the event, it doesn't fire them), and the Watcher
is in fact the notifier (it's the watcher that creates an event and calls the newEvent
method).
I'll use the terms observable and observer from now on. The observable fires events, and thus calls the observer's newEvent method.
If you want the event handling to be done in a separate thread, use a BlockingQueue
. Start a thread that loops endlessly, and tries to take()
from the queue at each iteration. Register an observer to the observable, which simply takes the received event and put()
it in the blocking queue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With