📄 04 - terminating a thread.rb
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -