title: Ruby 1.9.3-p140 - Using Thread - how to wait for all results to come out from threads?
body: <p>I'm trying to figure out a good way to wait for all threads to be executed before the main thread finishes.</p>
  
  <p>How can I do that in the following code?</p>
  
  <pre><code>    threads = []
  
      counter = 1000
  
      lines = 0
  
      counter.times do |i|
        puts "This is index number #{i}."
      end
  
      puts "You've just seen the normal printing and serial programming.\n\n"
  
      counter.times do |i|
        Thread.new do
          some_number = Random.rand(counter)
          sleep 1
          puts "I'm thread number #{i}. My random number is #{some_number}.\n"
          lines += 1
        end
      end
  
      messaged = false
      while lines &lt; 1000
        puts "\nWaiting to finish.\n" unless messaged
        print '.'
        puts "\n" if lines == 1000
        messaged = true
      end
  
      puts "\nI've printed #{lines} lines.\n"
      puts "This is end of the program."
  </code></pre>
  
  <p>The program puts the I'm thread number XXX. My random number is YYY mixed with the dots from the while loop almost at the end of the main thread. If I don't use the while loop, the program finishes before the threads finish.</p>