Ruby on Rails 入门之:(17) 初次接触ruby线程

本文介绍了一个Ruby多线程程序的实例,展示了如何通过使用.join方法确保主线程等待子线程完成,从而正确地显示线程输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

源码:

[ruby]  view plain copy
  1. i=1  
  2. puts "hello thread"  
  3. puts Time.new  
  4.   
  5. #round=5  
  6. #while i<round  
  7. #   puts "the #{i}th round"  
  8. #   i=i+1  
  9. #end  
  10.   
  11. thread1=Thread.start 10 do |value|  
  12.     while i<value  
  13.         puts "#{i}"  
  14.         i=i+1  
  15.     end  
  16. end  
  17.   
  18. thread2=Thread.start do   
  19.     10.times do |a|  
  20.         puts "the #{a+1} output"  
  21.     end  
  22. end  

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

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

[ruby]  view plain copy
  1. i=1  
  2. puts "hello thread"  
  3. puts Time.new  
  4.   
  5. #round=5  
  6. #while i<round  
  7. #   puts "the #{i}th round"  
  8. #   i=i+1  
  9. #end  
  10.   
  11. thread1=Thread.start 10 do |value|  
  12.     while i<value  
  13.         puts "#{i}"  
  14.         i=i+1  
  15.     end  
  16. end  
  17. thread1.join  
  18.   
  19. thread2=Thread.start do   
  20.     10.times do |a|  
  21.         puts "the #{a+1} output"  
  22.     end  
  23. end  
  24. thread2.join  

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

[html]  view plain copy
  1. hello thread  
  2. 2012-07-28 12:51:12 +0800  
  3. 1  
  4. 2  
  5. 3  
  6. 4  
  7. 5  
  8. 6  
  9. 7  
  10. 8  
  11. 9  
  12. the 1 output  
  13. the 2 output  
  14. the 3 output  
  15. the 4 output  
  16. the 5 output  
  17. the 6 output  
  18. the 7 output  
  19. the 8 output  
  20. the 9 output  
  21. the 10 output  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值