2012-12-21 36 views
-2

我是新來的紅寶石。我創建了一個名爲站這樣的類:線程和類

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?

我嘗試以下,但ofcouse它不工作

st = Thread.new{ Station.new()} 
while(true) 
    sleep(1) 
    puts st.get_no_crates() 
end 
+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 
+0

JazakAllah Khair –

+0

JazakAllah Khair再次爲更好的版本 –