第一次写一个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