我有这段代码:
5.times do |num|
puts "Spawning thread ##{num}"
Thread.new {
fun
puts "Thread ##{num} is done"
}
end
fun
需要很长时间才能完成,因此主线程已经退出。我知道我可以使用sleep
,但如果fun
花费的时间比预期的要长呢?如何在不阻塞的情况下无限期地暂停主线程?
答案 0 :(得分:2)
如documentation for Thread
所述,您必须join
主题:
def fun
sleep 2
end
threads = []
5.times do |num|
puts "Spawning thread ##{num}"
threads << Thread.new {
fun
puts "Thread ##{num} is done"
}
end
threads.each(&:join)
输出:
Spawning thread #0
Spawning thread #1
Spawning thread #2
Spawning thread #3
Spawning thread #4
并在2秒后:
Thread #4 is done
Thread #0 is done
Thread #1 is done
Thread #3 is done
Thread #2 is done