Skip to content

Instantly share code, notes, and snippets.

@steelThread
Last active December 20, 2015 01:39
Show Gist options
  • Save steelThread/6050207 to your computer and use it in GitHub Desktop.
Save steelThread/6050207 to your computer and use it in GitHub Desktop.
Executor - Producer-Consumer
import java.util.concurrent.Executors
module ProducerConsumer
def self.do_work
trap :TERM , -> { Executor.shutdown }
trap :INT , -> { Executor.shutdown }
Executor.execute Producer.new
end
module Executor
def self.execute(job)
executor.execute job
end
def self.shutdown
$terminate = true
puts 'Shutting down'
executor.shutdown
executor.await_termination 1, TimeUnit::MINUTES
puts 'Buh Bye'
end
def self.executor
@executor ||= Executors.new_fixed_thread_pool 2
end
end
class Producer
import java.lang.Runnable
def run
puts 'produce'
Executor.execute Consumer.new unless $terminate
end
end
class Consumer
import java.lang.Runnable
def run
puts 'consume'
Executor.execute Producer.new unless $terminate
sleep 1
end
end
end
ProducerConsumer.do_work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment