終止執行緒
如果執行緒到達其程式碼塊的末尾,則該執行緒終止。提前終止執行緒的最好方法是說服它到達其程式碼塊的末尾。這樣,執行緒可以在死亡之前執行清理程式碼。
該例項變數 continue 為 true 時,該執行緒執行迴圈。將此變數設定為 false,執行緒將自然死亡:
require 'thread'
class CounterThread < Thread
def initialize
@count = 0
@continue = true
super do
@count += 1 while @continue
puts "I counted up to #{@count} before I was cruelly stopped."
end
end
def stop
@continue = false
end
end
counter = CounterThread.new
sleep 2
counter.stop