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]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章