Running Threads

Here is a simple fix to the thread-running problem. Right at the end of the code, add this:

threads2.rb

sleep( 5 )

This inserts a five-second delay. Now when you run the code again, you should see all the strings and all the numbers, albeit a bit jumbled up, like this:

hello1

2world
3

4goodbye

5mars
6
7
8
9

This is, in fact, exactly what you want since it shows that time is now being divided between the two threads. That’s why the words and numbers are jumbled, sometimes with even the carriage returns printed by the puts statements being mixed up, with either no carriage return or two at once being displayed. This happens because the threads are madly competing with one another for the available time—first one thread executes and displays ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.