ruby线程编程,ruby相当于java wait / notify / notifyAll

我想知道ruby的Java方法的替代品是什么:

  • 等待
  • 通知
  • notifyAll的

你能发一个小片段或一些链接吗?

根据你的评论,我不知道Java的警告,我认为你想要一个条件变量。 谷歌的“Ruby条件变量”提出了一堆有用的页面。 我得到的第一个链接似乎是对条件变量的一个很好的快速介绍,而这看起来它提供了更广泛的Ruby中的线程编程的覆盖范围。

您正在寻找的是Thread ConditionVariable

 require "thread" m = Mutex.new c = ConditionVariable.new t = [] t << Thread.new do m.synchronize do puts "A - I am in critical region" c.wait(m) puts "A - Back in critical region" end end t << Thread.new do m.synchronize do puts "B - I am critical region now" c.signal puts "B - I am done with critical region" end end t.each {|th| th.join } 

没有相当于notifyAll(),但另外两个是Thread.stop (停止当前线程)并run (在已停止的线程上调用以使其再次开始)。

我想你正在寻找更像这样的东西。 它将适用于执行此操作后实例化的任何对象。 它并不完美,特别是在Thread.stop位于互斥锁之外的情况下。 在java中,等待一个线程,释放一个监视器。

 class Object def wait @waiting_threads = [] unless @waiting_threads @monitor_mutex = Mutex.new unless @monitor_mutex @monitor_mutex.synchronize { @waiting_threads << Thread.current } Thread.stop end def notify if @monitor_mutex and @waiting_threads @monitor_mutex.synchronize { @waiting_threads.delete_at(0).run unless @waiting_threads.empty? } end end def notify_all if @monitor_mutex and @waiting_threads @monitor_mutex.synchronize { @waiting_threads.each {|thread| thread.run} @waiting_threads = [] } end end end 

我想你想要的是Thread#join

 threads = [] 10.times do threads << Thread.new do some_method(:foo) end end threads.each { |thread| thread.join } #or threads.each(&:join) puts 'Done with all threads'