package org.eredlab.g4.rif.pushlet.core; import org.eredlab.g4.rif.pushlet.util.Log; /** * Abstract Event source from which Events are pulled. * * @author * @since 2011-05-12 */ abstract public class EventPullSource implements EventSource, Runnable { private volatile boolean alive = false; private volatile boolean active = false; private static int threadNum = 0; private Thread thread; public EventPullSource() { } abstract protected long getSleepTime(); abstract protected Event pullEvent(); public void start() { thread = new Thread(this, "EventPullSource-" + (++threadNum)); thread.setDaemon(true); thread.start(); } public boolean isAlive() { return alive; } /** * Stop the event generator thread. */ public void stop() { alive = false; if (thread != null) { thread.interrupt(); thread = null; } } /** * Activate the event generator thread. */ synchronized public void activate() { if (active) { return; } active = true; if (!alive) { start(); return; } Log.debug(getClass().getName() + ": notifying..."); notifyAll(); } /** * Deactivate the event generator thread. */ public void passivate() { if (!active) { return; } active = false; } /** * Main loop: sleep, generate event and publish. */ public void run() { Log.debug(getClass().getName() + ": starting..."); alive = true; while (alive) { try { Thread.sleep(getSleepTime()); // Stopped during sleep: end loop. if (!alive) { break; } // If passivated wait until we get // get notify()-ied. If there are no subscribers // it wasts CPU to remain producing events... synchronized (this) { while (!active) { Log.debug(getClass().getName() + ": waiting..."); wait(); } } } catch (InterruptedException e) { break; } try { // Derived class should produce an event. Event event = pullEvent(); // Let the publisher push it to subscribers. Dispatcher.getInstance().multicast(event); } catch (Throwable t) { Log.warn("EventPullSource exception while multicasting ", t); t.printStackTrace(); } } Log.debug(getClass().getName() + ": stopped"); } }
EventPullSource源码分享
最新推荐文章于 2023-07-07 12:01:13 发布