美文网首页
线程的基本操作

线程的基本操作

作者: GALAXY_ZMY | 来源:发表于2015-08-30 23:34 被阅读59次

    线程的创建可以使用Thread.new,Thread.start 或者Thread.fork来创建线程。例如thread = Thread.new {}。
    i=1
    thread1=Thread.start 10 do |value| while i<value puts "#{i}" i=i+1 end end thread1.join thread2=Thread.start do 10.times do |a| puts "the #{a+1} output" end end thread2.join
    线程thread1线程创建以后,调用了thread1.join方法挂起主线程,等待thread1线程完成,这样就能在主线程结束之前看到线程thread1,thread2的输出消息。

    但是这样可以看到,线程的输出是等到线程thread1完全执行完毕以后才执行线程thread2,线程的调度是随机的,所以如果没有thread1.join和thread2.join两个方法,线程的输出就会变得没有规律
    通过Thread.current方法可以获得线程的id。
    i=1 thread1=Thread.start 10 do |value| while i<value id=Thread.current puts "#{i} 当前执行的线程id:#{id}\n" i=i+1 end end thread2=Thread.start do 10.times do |a| id=Thread.current puts "the #{a+1} 当前执行的线程id:#{id}\n" end end thread1.join thread2.join

    线程的停止

    可以使用Thread.exit停止当前线程。
    i=1 thread1=Thread.start 10 do |value| while i<value puts "#{i} \n" i=i+1 if i>3 Thread.exit end end end thread1.join
    当thead1线程中i超过3以后,结束那个线程。
    同时线程的结束还可以使用Thread.pass。

    使用sleep函数让线程休眠

    i=1 puts "hello thread" puts Time.new thread1=Thread.start 10 do |value| sleep 3 while i<value puts "#{i} \n" i=i+1 end end thread1.join

    可以使用 Thread.current 方法来访问当前线程
    使用 Thread.list 方法列出所有线程;
    可以使用Thread.status 和 Thread.alive? 方法得到线程的状态;
    可以使用 Thread.priority 方法得到线程的优先级和使用 Thread.priority= 方法来调整线程的优先级,默认为0,可以设置为-1,-2等

    数据互访

    Thread 类提供了线程数据互相访问的方法,你可以简单的把一个线程作为一个 Hash 表,可以在任何线程内使用 []=写入数据,使用 []读出数据。
    `athr = Thread.new { Thread.current["name"] = "Thread A"; Thread.stop }

    bthr = Thread.new { Thread.current["name"] = "Thread B"; Thread.stop }

    cthr = Thread.new { Thread.current["name"] = "Thread C"; Thread.stop }

    Thread.list.each {|x| puts "#{x.inspect}: #{x["name"]}" }'
    可以看到,把线程作为一个 Hash 表,使用 [] 和 []= 方法,我们实现了线程之间的数据共享。

    相关文章

      网友评论

          本文标题:线程的基本操作

          本文链接:https://www.haomeiwen.com/subject/ceakcttx.html