本意是想模拟一下线程不安全的情况,于是写了一下代码,创建 2 个线程共用 1 个变量,每个线程里面将共用变量 number 减 1
arr = []
number = 10
2.times do |i|
arr << Thread.new do
puts "t#{i} 剩余#{number}颗豆子\n"
while(number != 0 ) do
sleep(1)
puts "t#{i} 剩余#{number}颗豆子\n"
number -= 1
# puts "t#{i} 减去1颗后,剩余#{number}颗豆子\n"
end
end
end
但是一旦将 puts 语句放在 number -= 1 下方,就又不会出现这种问题了,这到底是为何
arr = []
number = 10
2.times do |i|
arr << Thread.new do
puts "t#{i} 剩余#{number}颗豆子\n"
while(number != 0 ) do
sleep(1)
#puts "t#{i} 剩余#{number}颗豆子\n"
number -= 1
puts "t#{i} 减去1颗后,剩余#{number}颗豆子\n"
end
end
end