线程和类

时间:2012-12-21 04:06:08

标签: ruby multithreading class

我是红宝石的新手。我创建了一个名为Station的类:

class Station

  def initialize()
    @no_crates = 5
    while(true)
      sleep(1)
      @no_crates = Integer(@no_crates) + 1
    end
  end

  def get_no_crates()
    return @no_crates
  end
end

变量@no_crates应该随着时间的推移而增加,所以我想在一个单独的线程中运行这个类。我怎么能这样做,然后不时调用get_no_crates()函数来获取@no_crates?

我尝试了以下但是不能正常工作

st =  Thread.new{ Station.new()}
while(true)
  sleep(1)
  puts st.get_no_crates()
end

1 个答案:

答案 0 :(得分:3)

看到这一点,试着去理解你做错了什么。

class Station

  def initialize()
    @no_crates = 5
  end

  def run
    while(true)
      sleep(1)
      @no_crates = Integer(@no_crates) + 1
    end
  end

  def get_no_crates()
    return @no_crates
  end
end


station = Station.new
st =  Thread.new{ station.run }
while(true)
  sleep(1)
  puts station.get_no_crates()
end

这是一个更好看的版本

class Station

  attr_reader :no_crates

  def initialize
    @no_crates = 5
  end

  def run
    loop do
      sleep 1
      @no_crates = @no_crates + 1
    end
  end
end

station = Station.new
st =  Thread.new{ station.run }
loop do
  sleep 1 
  puts station.no_crates
end