這篇文章主要介紹了Ruby實現生產者和消費者代碼分享,本文直接給出實現代碼,需要的朋友可以參考下
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #ruby實現生產者和消費者代碼 require 'thread' queue = Queue.new consumers = Thread.new do 5.times do |i| obj = queue.pop print "consumer :#{i}n" sleep(rand(0.05)) end end producters = Thread.new do 5.times do |i| sleep(0.1) print "producter : #{i}n" queue.push("Item #{i}") end end producters.join consumers.join