首先,是否有一個主線程(在我的情況下爲t2
),開始和結束所有其他線程(t1
)的標準?如何使用Ruby線程
require 'curses'
include Curses
init_screen
def counter(window_name, positionx, positiony, times_factor, sleep_factor)
window_name = Window.new(10,10,positionx,positiony)
window_name.box('|', '-')
window_name.setpos(2, 3)
window_name.addstr(window_name.inspect)
times_factor.times do |i|
window_name.setpos(1, 1)
window_name.addstr(i.to_s)
window_name.refresh
sleep sleep_factor
end
end
def thread1
counter("One",10,10,50,0.01)
counter("Two",20,20,200,0.01)
counter("Three",30,30,3,1.0)
end
def thread2
t1 = Thread.new{thread1()}
x = 4
chars = [" ","* ","** ","***","***","** ","* "," "]
four = Window.new(20,20,10,100)
four.box('|', '-')
four.setpos(1, 1)
i = 3
while t1.alive?
four.setpos(1, 1)
four.addstr chars[0]
four.addstr i.to_s
four.refresh
sleep 0.1
chars.push chars.shift
end
t1.join
end
t2 = Thread.new{thread2()}
t2.join
其次,我怎樣才能改變while t1.alive?
循環,這樣,而不是t1
操作過程中只是顯示一個明星動畫,我可以給什麼t1
線程中實際發生的情況的反饋?例如,
counter1 has now finished
counter2 has now finished
counter3 has now finished
要做到這一點,將每個櫃檯方法實際上必須要在內部t1
自己的線程?在while t1.alive?
循環中,我是否應該有一個能夠持續測試哪個循環當前還在運行的情況循環?
這種方法意味着整個程序正在發生,而不是按照其寫入的順序。這是大型程序實際工作的方式嗎?這是我應該如何提供反饋?只有在某個線程已加入時才告訴用戶?