Bird
0
0

You want to create 3 threads that each print their thread number (1, 2, 3) and then print 'Finished' after all threads complete. Which code correctly achieves this?

hard📝 Application Q15 of 15
Ruby - Concurrent Programming
You want to create 3 threads that each print their thread number (1, 2, 3) and then print 'Finished' after all threads complete. Which code correctly achieves this?
A3.times do |i| Thread.new { puts i + 1 } end puts 'Finished'
Bthreads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished'
Cthreads = [] 3.times do |i| threads << Thread.new { puts i } end puts 'Finished' threads.each(&:join)
Dthreads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end puts 'Finished' threads.each(&:join)
Step-by-Step Solution
Solution:
  1. Step 1: Create threads storing them in an array

    threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished' correctly creates 3 threads, each printing i + 1 (1, 2, 3), and stores them in threads.
  2. Step 2: Wait for all threads to finish before printing 'Finished'

    threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished' calls threads.each(&:join) to wait for all threads, then prints 'Finished'. This ensures 'Finished' prints last.
  3. Final Answer:

    threads = [] 3.times do |i| threads << Thread.new { puts i + 1 } end threads.each(&:join) puts 'Finished' -> Option B
  4. Quick Check:

    Store threads, join all, then print [OK]
Quick Trick: Join all threads before printing final message [OK]
Common Mistakes:
  • Not storing threads to join later
  • Printing 'Finished' before threads complete
  • Using wrong thread index values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes