04 - terminating a thread.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 86 行

RB
86
字号
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  endendcounter = CounterThread.newsleep 2counter.stop# I counted up to 3413544 before I was cruelly stopped.#---t = Thread.new { loop { puts 'I am the unstoppable thread!' } }# I am the unstoppable thread!# I am the unstoppable thread!# I am the unstoppable thread!# I am the unstoppable thread!t.terminate#---class LoopingThread < Thread  def initialize    @stopped = false    @paused = false    super do       before_loop      until @stopped        yield        Thread.stop if @paused      end      after_loop    end  end    def before_loop; end  def after_loop; end  def stop    @stopped = true  end  def paused=(paused)    @paused = paused    run if !paused  endend#---class PausableCounter < LoopingThread  attr_reader :count  def before_loop    @count = 0  end  def initialize    super { @count += 1 }  end  def after_loop    puts "I counted up to #{@count} before I was cruelly stopped."        endendcounter = PausableCounter.newsleep 2counter.paused = truecounter.count                                              # => 819438sleep 2counter.count                                              # => 819438counter.paused = falsesleep 2counter.stop# I counted up to 1644324 before I was cruelly stopped.counter.count                                              # => 1644324#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?