初次接触ruby线程

来源:互联网 发布:推荐一部电影 知乎 编辑:程序博客网 时间:2024/06/05 09:54

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

源码:

i=1puts "hello thread"puts Time.new#round=5#while i<round#puts "the #{i}th round"#i=i+1#endthread1=Thread.start 10 do |value| while i<valueputs "#{i}"i=i+1endendthread2=Thread.start do 10.times do |a|puts "the #{a+1} output"endend

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

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

i=1puts "hello thread"puts Time.new#round=5#while i<round#puts "the #{i}th round"#i=i+1#endthread1=Thread.start 10 do |value| while i<valueputs "#{i}"i=i+1endendthread1.jointhread2=Thread.start do 10.times do |a|puts "the #{a+1} output"endendthread2.join

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

hello thread2012-07-28 12:51:12 +0800123456789the 1 outputthe 2 outputthe 3 outputthe 4 outputthe 5 outputthe 6 outputthe 7 outputthe 8 outputthe 9 outputthe 10 output


原创粉丝点击