Ruby on Rails 入门之:(20) ruby线程控制的join

来源:互联网 发布:淘宝上文玩核桃哪家好 编辑:程序博客网 时间:2024/06/05 03:10

所有的编程语言中的线程控制都使用了join,可能鉴于英语和汉语的差异,这个函数功能让我们理解起来相当的费解。


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}\n"i=i+1sleep(0.1);endendthread1.jointhread2=Thread.start do 10.times do |a|puts "the #{a+1} output\n"sleep(0.1);endendthread2.join

第一个thread1.join, 意思是挂起主线程,执行我们指定的线程,即thread1,所以可以这样理解,哪个线程调用join函数,就是执行哪个线程,而挂起执行这个线程之前的线程。


看看上面程序的输出结果:


watkins@watkins:~/temp/workspace/ruby$ ruby thread1.rb hello threadWed Oct 10 12:07:28 +0800 2012123456789the 1 outputthe 2 outputthe 3 outputthe 4 outputthe 5 outputthe 6 outputthe 7 outputthe 8 outputthe 9 outputthe 10 outputwatkins@watkins:~/temp/workspace/ruby$ 

可以看到,直到线程thread1执行完毕之后才执行的thread2.


那么如果没有使用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}\n"i=i+1sleep(0.1);endend#thread1.jointhread2=Thread.start do 10.times do |a|puts "the #{a+1} output\n"sleep(0.1);endendthread2.join

这时候获得的输出是thread1和thread2混合的输出:

watkins@watkins:~/temp/workspace/ruby$ ruby thread1.rb hello threadWed Oct 10 12:39:16 +0800 20121the 1 outputthe 2 output2the 3 output3the 4 output4the 5 output5the 6 output6the 7 output7the 8 output8the 9 output9the 10 outputwatkins@watkins:~/temp/workspace/ruby$