join
当要加入的线程尚未完成时,调用线程将阻塞父线程。为了检查这一点,我创建了以下代码:
threads = []
3.times do |i|
threads << Thread.new do
3.times do |j|
puts "Thread #{i} says #{j} (#{Thread.current})"
sleep 0.1
end
end
end
#threads.map(&:join)
threads[0].join
puts "After first join"
threads[1].join
puts "After second join"
threads[2].join
puts "Last line of main thread"
运行这样的代码会给出以下输出:
Thread 0 says 0 (#<Thread:0x007fdceb0b8568>)
Thread 2 says 0 (#<Thread:0x007fdce982bb08>)
Thread 1 says 0 (#<Thread:0x007fdceb0b8450>)
Thread 0 says 1 (#<Thread:0x007fdceb0b8568>)
Thread 1 says 1 (#<Thread:0x007fdceb0b8450>)
Thread 2 says 1 (#<Thread:0x007fdce982bb08>)
Thread 1 says 2 (#<Thread:0x007fdceb0b8450>)
Thread 2 says 2 (#<Thread:0x007fdce982bb08>)
Thread 0 says 2 (#<Thread:0x007fdceb0b8568>)
After first join
After second join
Last line of main thread
为什么 rubyAfter first join
会在线程指令之后打印,尽管该指令threads[1].join
是在该打印指令之后执行的?