Threads let your program do many things at the same time. This helps make your program faster and more responsive.
0
0
Thread creation and execution in Ruby
Introduction
When you want to download multiple files at once.
When you want to run a timer while your program waits for user input.
When you want to do background work without stopping the main program.
When you want to handle many tasks that can run independently.
When you want to keep your program responsive during long operations.
Syntax
Ruby
thread = Thread.new do # code to run in the thread end thread.join # wait for the thread to finish
The Thread.new method starts a new thread and runs the code inside the block.
Use thread.join to wait for the thread to finish before continuing.
Examples
This creates a thread that prints a message, then waits for it to finish.
Ruby
thread = Thread.new do puts "Hello from thread!" end thread.join
This creates two threads that print messages independently, then waits for both.
Ruby
thread1 = Thread.new { puts "First thread" } thread2 = Thread.new { puts "Second thread" } thread1.join thread2.join
This thread counts from 0 to 2 with a 1-second pause between each count.
Ruby
thread = Thread.new do 3.times do |i| puts "Count: #{i}" sleep(1) end end thread.join
Sample Program
This program starts a thread that counts to 4 with pauses. Meanwhile, the main program prints a message and waits for the thread to finish before printing the last message.
Ruby
thread = Thread.new do 5.times do |i| puts "Thread counting: #{i}" sleep(0.5) end end puts "Main program continues" thread.join puts "Thread finished"
OutputSuccess
Important Notes
Threads share the same memory space, so be careful when changing shared data.
Use sleep to pause a thread without stopping the whole program.
Always join threads if you want to wait for them to finish before ending the program.
Summary
Threads let your program do many things at once.
Create threads with Thread.new and run code inside a block.
Use join to wait for threads to finish.