/ Published in: Ruby
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
require "java" require "jetlang-0.2.0.jar" include_class "org.jetlang.fibers.ThreadFiber" include_class "org.jetlang.channels.MemoryChannel" include_class "org.jetlang.channels.BatchSubscriber" include_class "java.util.concurrent.CountDownLatch" include_class "java.util.concurrent.TimeUnit" class PingPongChannels def ping return @ping_channel ||= MemoryChannel.new end def pong return @pong_channel ||= MemoryChannel.new end def stop return @stop_channel ||= MemoryChannel.new end end class Ping def initialize(channels, fiber, count) @channels = channels @consumer = fiber @count = count end def start on_receive = Proc.new do |message| if @count > 0 publish_ping(message) else @channels.stop.publish("") @consumer.dispose end end @channels.ping.subscribe(@consumer, on_receive) @consumer.start end def publish_ping(message) puts message @count -= 1 @channels.pong.publish("From ping to pong") end end class Pong def initialize(channels, fiber) @channels = channels @consumer = fiber end def start on_receive = Proc.new do |message| puts message @channels.ping.publish("From pong to ping") end @channels.pong.subscribe(@consumer, on_receive) on_stop = Proc.new {|message| @consumer.dispose} @channels.stop.subscribe(@consumer, on_stop) @consumer.start end end channels = PingPongChannels.new ping_thread = ThreadFiber.new pong_thread = ThreadFiber.new ping = Ping.new(channels, ping_thread, 1000) pong = Pong.new(channels, pong_thread) pong.start ping.start channels.ping.publish("Start Game") ping_thread.join pong_thread.join