Thread in Ruby(1)

Thread is a very important concept in every computer language,for example in java,in c++ or in c.So Ruby have its own Thread concept.

[b]Create a new Thread[/b]

If you want to create a new thread in java,there are two ways(first,you can write a class which extend the java.lang.Thread class;second,you can implement the java.lang.Runable interface).But in ruby,there is only one way to create a thread.Because you can pass a block into every function,you shouldn't write your own class to extend a class or include a module,you only need write a block which contains all codes you want to do and pass it into the new method of Thread.The following is a sample:
[code]t1 = Thread.new { puts "Create a new Thread"}[/code]
There are some differences between java and ruby.After you create a Thread instance,you need call the run method of the Thread instance to run the thread in Java.But in ruby,when you call the new method,you start the thread which you create.Second,you can get a return value from a thread,(The thread should return the last expression in the block passed into Thread.new method).You can use the value attribute to access the return value.
[b]
Manage the Thread[/b]

As the same in java,you can control a thread with some methods of the Thread class.You can control a thread in ruby,too.The following is a list of these methods which can control a thread:
[list]
kill
pass:like the wait method in java
stop:set the current thread in sleep status.The defference between stop and [/list]sleep is that there is not a sleep time parameter which should be passed to the stop method.
exit:
join:
priority=:set a thread the priority value.
raise:throw an exception in another exception
run:like notify(?I have some doubt about it)
terminate:
wakeup:
[/list]
There are some methods to access a thread's status:

main:return the main thread in this process(There is not a same method in java)
alive?
stop?
status

[b]Share thread variable[/b]

You can set some variables in thread and then you can access these variables in other threads if they have the reference of the thread.This usage like the ThreadLocal class in java,but they have many differences.
[code]
thread = Thread.new do
t = Thread.current
t[:var1] = "This is a string"
t[:var2] = 365
end

# Access the thread-local data from outside...

x = thread[:var1] # "This is a string"
y = thread[:var2] # 365

has_var2 = thread.key?("var2") # true
has_var3 = thread.key?("var3") # false
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值