2012-09-09 105 views
0

下面的代碼拋出消息而不用換行符。Ruby - 爲什麼Thread不尊重方法?

threads = [] 
counter = 1000 
counter.times do 
    threads << Thread.new do 
     puts "This is a line." 
     sleep 1 
    end 
end 

threads.each {|t| t.join} 

結果是

This is a line. This is a line 

This is a line. 
This is a line. 

and so on... 

反正有打印結果行以整潔的方式嗎?

+0

這是jruby嗎?我不認爲你在MRI中會出現這種情況。 – pguardiario

+0

它來自MRI 1.9.3-p130。 –

回答

2

puts通過打印其參數在內部工作,然後通過打印換行符。有時,這兩個操作之間的線程會中斷,導致您看到的行爲。你可以說:

print "This is a line.\n" 

...這將寫在整個字符串 - 包括換行 - 在一個單一的操作。

相關問題