我想创建一个脚本来计算多个线程中的数字。每个线程将计算 2 的幂,但第一个线程必须从 2 开始计算,第二个线程从 4 开始计算,第三个线程从 8 开始计算,在中间打印一些文本。
例子:
Im a thread and these are my results
2
4
8
Im a thread and these are my results
4
8
16
Im a thread and these are my results
8
16
32
我的失败代码:
def loopa(s)
3.times do
puts s
s=s**2
end
end
threads=[]
num=2
until num == 8 do
threads << Thread.new{ loopa(num) }
num=num**2
end
threads.each { |x| puts "Im a thread and these are my results" ; x.join }
我的失败结果:
Im a thread and these are my results
8
64
4096
8
64
4096
8
64
4096
Im a thread and these are my results
Im a thread and these are my results