【问题标题】:Stop Ruby - jRuby - thread after a certain time停止 Ruby - jRuby - 特定时间后的线程
【发布时间】:2012-02-25 13:41:35
【问题描述】:

我正在尝试使用 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

我已经尝试了几个 if 的东西,例如:

# 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。任何提示/建议将不胜感激。

【问题讨论】:

    标签: ruby multithreading jruby


    【解决方案1】:

    我想我解决了。

    这成功了:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-09-25
      • 2017-01-30
      • 2011-12-08
      • 1970-01-01
      • 2020-08-28
      • 2015-05-04
      • 2016-12-13
      • 1970-01-01
      • 2012-07-31
      相关资源
      最近更新 更多