Ruby:Thread没有运行

时间:2016-01-08 16:59:13

标签: ruby

我在Ruby学习线程。

我创建了一个帖子,但它不起作用。 我该如何解决?

puts 'start'
Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end

puts 'start 2'

输出:

  

开始
  开始2

2 个答案:

答案 0 :(得分:3)

问题是主线程在没有执行其他线程的情况下结束。您必须使主线程等待它使用Thread#join完成:

puts 'start'
Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end.join

puts 'start 2'

答案 1 :(得分:0)

puts 'start'

t = Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end

t.join

puts 'start 2'

puts 'start'

Thread.new do
  puts 'thread'
  10.times { |i| puts i  }
end.join

puts 'start 2'
相关问题