ADVERTISEMENT
ADVERTISEMENT

Ruby program to sleep thread execution for a specific time

Ruby Example: Write a program to sleep thread execution for a specific time.
Submitted by Nidhi, on February 13, 2022

Problem Solution:

In this program, we will create two threads. Here, we will use the sleep() method to pause a thread for a specific time.

Program/Source Code:

The source code to sleep thread execution for a specific time is given below. The given program is compiled and executed on Windows 10 Operating System successfully.

# Ruby program to sleep thread execution 
# for a specific time.

# First Thread method
def ThreadFun1()
	$i = 0;
	while $i<5 do
		puts "First Thread running";
		$i += 1;

		# sleep thread for 1 second
		sleep(1);
	end
end

# Second Thread method
def ThreadFun2()
	$i = 0;
	while $i<5 do
		puts "Second Thread running";
		$i += 1;

		# sleep thread for 1 second
		sleep(1);
	end
end

# Create thread objects
t1 = Thread.new{ThreadFun1()};
t2 = Thread.new{ThreadFun2()};

# Join created thread.
t1.join();
t2.join();

Output:

First Thread running
Second Thread running
Second Thread running
First Thread running
Second Thread running
First Thread running

Explanation:

In the above program, we created two methods ThreadFun1(), ThreadFun2(). Then we bound the methods with thread objects. Here, we used the sleep() method to pause thread execution and printed the messages.

Ruby Threading Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.