Ruby中的线程

Ruby线程

在Ruby中,借助线程,您可以同时实现多个进程,或者可以说Thread支持并发编程模型。除了主线程之外,您还可以借助“ new”关键字创建线程。线程是轻量级的,您可以借助以下语法来创建线程:

Thread_name = Thread.new{#statement}

现在,让我们看看如何在一个支持示例的帮助下在Ruby中创建线程

=begin
Ruby program to demonstrate threads	
=end

thr = Thread.new{puts "Hello! Message from Nhooo"}
thr.join

输出结果

Hello! Message from Nhooo

在上面的示例中,我们创建了一个名为thr的线程。Thr是Thread类的实例,在线程主体内部,我们使用字符串调用puts方法。thr.join方法用于启动线程的执行。

现在,让我们创建一个用户定义的方法,并通过以下方式在线程内调用它:

=begin
Ruby program to demonstrate threads	
=end

def Nhooo1 
a = 0
while a <= 10
	puts "Thread execution: #{a}"

	sleep(1) 

	a = a + 1
    end
end

x = Thread.new{Nhooo1()} 
x.join

输出结果

Thread execution: 0
Thread execution: 1
Thread execution: 2
Thread execution: 3
Thread execution: 4
Thread execution: 5
Thread execution: 6
Thread execution: 7
Thread execution: 8
Thread execution: 9
Thread execution: 10

在上面的代码中,我们正在创建Thread类名称为x的实例。在线程体内,我们正在调用用户定义的方法Nhooo1。我们将循环变量打印10次。在循环内部,我们容纳了sleep方法,该方法将暂停执行1秒钟。我们将在join方法的帮助下开始执行线程。

=begin
Ruby program to demonstrate threads	
=end

def myname 
	for i in 1...10
		p = rand(0..90)
		puts "My name is Vaibhav #{p}"
		sleep(2) 
	end
end

x = Thread.new{myname()} 
x.join

输出结果

My name is Vaibhav 11
My name is Vaibhav 78
My name is Vaibhav 23
My name is Vaibhav 24
My name is Vaibhav 82
My name is Vaibhav 10
My name is Vaibhav 49
My name is Vaibhav 23
My name is Vaibhav 52

在上面的代码中,我们创建了一个线程并在其中打印一些值。我们正在从rand方法和sleep方法获得帮助。

在本教程结束之前,您必须已经了解了线程类的用法以及我们如何创建其对象。