1
我試圖用jRuby創建一個簡單的多線程程序。它需要基於指定的時間量開始和停止線程,例如,運行五秒鐘然後停止。我對這類東西相當陌生,所以它可能很基本,但我無法讓它工作。停止紅寶石 - jRuby - 線程在一定時間後
相關的代碼如下所示:
require 'java'
require 'timeout'
require './lib/t1.rb'
require './lib/t2.rb'
class Threads
[...]
def manage_threads
thread2 = T2.new
# Wait for 5 seconds before the thread starts running..
thread2.run(wait_time = 5)
Timeout::timeout(10) do
thread1 = T1.new {}
end
end
class T1 < Thread
def initialize
while super.status != "sleep"
puts "Thread 1"
sleep(1)
end
end
end
class T2
include java.lang.Runnable
def run wait_time
thread = Thread.new do
sleep(wait_time)
loop do
puts "Thread 2"
sleep(1)
end
end
end
def stop_thread(after_run_time)
sleep(after_run_time)
end
end
我已經嘗試了,如果事情,例如:
# Used timeout
Timeout::timeout(10) do
thread1 = T1.new {}
end
# This kinda works, except that it terminates the program and therefore isn't the behavior
# I want.
有沒有人對如何1.啓動一個線程的建議,運行一段時間。 2.開始一個新線程,並行運行兩個線程。 2.停止線程1,但繼續運行線程2.任何提示/建議,將不勝感激。