Q:

Ruby program to create multiple threads

belongs to collection: Ruby Threading Programs

0

In this program, we will create two methods and bind created methods with thread objects. Then we will execute both created threads.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create multiple threads is given below. The given program is compiled and executed on Windows 10 Operating System successfully.

# Ruby program to create multiple threads

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

# Second Thread method
def ThreadFun2()
	$i = 0;
	while $i<5 do
		puts "Second Thread running";
		$i += 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
First Thread running
First Thread running
First Thread running
First Thread running
Second Thread running
Second Thread running
Second Thread running
Second Thread running
Second Thread running

Explanation:

In the above program, we created two methods ThreadFun1()ThreadFun2(). Then we bound the methods with thread objects. After that, we used the join() method to execute threads and printed appropriate messages.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby program to sleep thread execution for a speci... >>
<< Ruby program to create a simple thread...