我正在尝试使用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.任何提示/建议将不胜感激。
答案 0 :(得分:0)
我想我解决了。
这就是诀窍:
def run wait_time
thread = Thread.new do
sleep(wait_time)
second_counter = 0
loop do
puts "Thread 2"
second_counter += 1
if second_counter == 15
sleep
end
sleep(1)
end
end
end