Thanks Robert and Jake. I must use threads. Actually my original problem 
is much more complicated and I just simplified it to ask in this forum.

I just found the ConditionVariable class, and it seems it is the key to 
implement such cooperation between threads.

Please help review my code below. Let me know if I did anything wrong.

(I have tested the code with both C Ruby and JRuby, and it works well.)
=====================================
require 'thread'

mutex = Mutex.new
resource = ConditionVariable.new
next_one = 'A'

a = Thread.new {
  while true
    mutex.synchronize {
      while next_one != 'A'
      resource.wait(mutex)
      end
    }
    puts "A..."
    next_one = 'B'
    mutex.synchronize {
      resource.signal
    }
  end
}

b = Thread.new {
  while true
    mutex.synchronize {
      while next_one != 'B'
      resource.wait(mutex)
      end
    }
    puts "B..."
    next_one = 'A'
    mutex.synchronize {
      resource.signal
    }
  end
}

a.join
b.join
exit

-- 
Posted via http://www.ruby-forum.com/.