初次接触ruby线程

第一次写一个ruby多线程程序。但是最初有点小问题

源码:

i=1
puts "hello thread"
puts Time.new

#round=5
#while i<round
#	puts "the #{i}th round"
#	i=i+1
#end

thread1=Thread.start 10 do |value|
 	while i<value
		puts "#{i}"
		i=i+1
	end
end

thread2=Thread.start do 
	10.times do |a|
		puts "the #{a+1} output"
	end
end

然后运行程序没有线程的运行输出。刚开始以为成为写错了,后来发现是主线程执行完毕,开启的线程还没有来得及显示数据就被关闭掉了。所以这个时候得不到任何关于线程的输出。

想要得到正确的输出,必须让线程有足够的时间来运行输出。可以加上.join来等待线程完成。

i=1
puts "hello thread"
puts Time.new

#round=5
#while i<round
#	puts "the #{i}th round"
#	i=i+1
#end

thread1=Thread.start 10 do |value|
 	while i<value
		puts "#{i}"
		i=i+1
	end
end
thread1.join

thread2=Thread.start do 
	10.times do |a|
		puts "the #{a+1} output"
	end
end
thread2.join

这个时候就可以得到线程的输出。

hello thread
2012-07-28 12:51:12 +0800
1
2
3
4
5
6
7
8
9
the 1 output
the 2 output
the 3 output
the 4 output
the 5 output
the 6 output
the 7 output
the 8 output
the 9 output
the 10 output


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值