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

本文通过示例详细解析了编程中线程控制的核心方法——join函数的功能。解释了join如何挂起主线程并确保指定线程的执行完成,对比了使用与不使用join时程序的不同行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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函数,就是执行哪个线程,而挂起执行这个线程之前的线程。


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


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会获得什么样的输出呢?看看


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混合的输出:

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$ 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值