Ruby on Rails 入门之:(20) ruby线程控制的join
所有的编程语言中的线程控制都使用了join,可能鉴于英语和汉语的差异,这个函数功能让我们理解起来相当的费解。
join方法给出的解释是:挂起当前线程,执行指定的线程.那么,到底是挂起哪个线程,执行哪个线程。
看看代码来解释:
[ruby]
i=1
puts "hello thread"
puts Time.new
#round=5
#while i<round
# puts "the #{i}th round"
# i=i+1
#end
thread1=Thread.start 10 do |value|
while i<value
puts "#{i}\n"
i=i+1
sleep(0.1);
end
end
thread1.join
thread2=Thread.start do
10.times do |a|
puts "the #{a+1} output\n"
sleep(0.1);
end
end
thread2.join
i=1
puts "hello thread"
puts Time.new
#round=5
#while i<round
# puts "the #{i}th round"
# i=i+1
#end
thread1=Thread.start 10 do |value|
while i<value
puts "#{i}\n"
i=i+1
sleep(0.1);
end
end
thread1.join
thread2=Thread.start do
10.times do |a|
puts "the #{a+1} output\n"
sleep(0.1);
end
end
thread2.join
第一个thread1.join, 意思是挂起主线程,执行我们指定的线程,即thread1,所以可以这样理解,哪个线程调用join函数,就是执行哪个线程,而挂起执行这个线程之前的线程。
看看上面程序的输出结果:
[html]
watkins@watkins:~/temp/workspace/ruby$ ruby thread1.rb
hello thread
Wed Oct 10 12:07:28 +0800 2012
1
2
3
4
5
6
7
8
9
the 1 output
the 2 output
the 3 output
the 4 output
the 5 output
the 6 output
the 7 output
the 8 output
the 9 output
the 10 output
watkins@watkins:~/temp/workspace/ruby$
watkins@watkins:~/temp/workspace/ruby$ ruby thread1.rb
hello thread
Wed Oct 10 12:07:28 +0800 2012
1
2
3
4
5
6
7
8
9
the 1 output
the 2 output
the 3 output
the 4 output
the 5 output
the 6 output
the 7 output
the 8 output
the 9 output
the 10 output
watkins@watkins:~/temp/workspace/ruby$
可以看到,直到线程thread1执行完毕之后才执行的thread2.
那么如果没有使用join会获得什么样的输出呢?看看
[ruby]
i=1
puts "hello thread"
puts Time.new
#round=5
#while i<round
# puts "the #{i}th round"
# i=i+1
#end
thread1=Thread.start 10 do |value|
while i<value
puts "#{i}\n"
i=i+1
sleep(0.1);
end
end
#thread1.join
thread2=Thread.start do
10.times do |a|
puts "the #{a+1} output\n"
sleep(0.1);
end
end
thread2.join
i=1
puts "hello thread"
puts Time.new
#round=5
#while i<round
# puts "the #{i}th round"
# i=i+1
#end
thread1=Thread.start 10 do |value|
while i<value
puts "#{i}\n"
i=i+1
sleep(0.1);
end
end
#thread1.join
thread2=Thread.start do
10.times do |a|
puts "the #{a+1} output\n"
sleep(0.1);
end
end
thread2.join
这时候获得的输出是thread1和thread2混合的输出:
[html]
watkins@watkins:~/temp/workspace/ruby$ ruby thread1.rb
hello thread
Wed Oct 10 12:39:16 +0800 2012
1
the 1 output
the 2 output
2
the 3 output
3
the 4 output
4
the 5 output
5
the 6 output
6
the 7 output
7
the 8 output
8
the 9 output
9
the 10 output
watkins@watkins:~/temp/workspace/ruby$
watkins@watkins:~/temp/workspace/ruby$ ruby thread1.rb
hello thread
Wed Oct 10 12:39:16 +0800 2012
1
the 1 output
the 2 output
2
the 3 output
3
the 4 output
4
the 5 output
5
the 6 output
6
the 7 output
7
the 8 output
8
the 9 output
9
the 10 output
watkins@watkins:~/temp/workspace/ruby$
补充:Web开发 , 其他 ,