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

来源:互联网 发布:黑莓priv淘宝靠谱么 编辑:程序博客网 时间:2024/05/16 00:59

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

源码:

[ruby] view plaincopy
  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 plaincopy
  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 plaincopy
  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  
原创粉丝点击