终止线程

如果线程到达其代码块的末尾,则该线程终止。提前终止线程的最好方法是说服它到达其代码块的末尾。这样,线程可以在死亡之前运行清理代码。

该实例变量 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