ruby线程实现生产者消费者问题示例(队列Queue实现线程同步)
Ruby线程实现经典的生产者消费者问题,用ruby中的Queue类实现线程同步问题。
代码如下:
require "thread" puts "ProAndCon" queue = Queue.new #用队列Queue实现线程同步 producer = Thread.new do 10.times do |i| sleep rand(i) # 让线程睡眠一段时间 queue << i puts "#{i} produced" end end consumer = Thread.new do 10.times do |i| value = queue.pop sleep rand(i/2) puts "consumed #{value}" end end consumer.join #等待consumer线程的输出完成再关闭此进程
相关推荐
PMJ0 2020-10-13
longzhiwen 2020-09-06
yangxingstar 2020-08-31
LUCIEN0 2020-08-17
huangzihao00 2020-08-17
Jan 2020-08-17
AndesStay 2020-06-12
afengxg 2020-06-09
zamesking 2020-06-09
afengxg 2020-06-09
何志文 2020-06-09
teresalxm 2020-06-05
何志文 2020-05-16
何志文 2020-05-11
fsl 2020-05-04
JOO 2020-04-26
倩 2020-04-22
afanti 2020-04-19
始终不够 2020-04-10