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

线程的基本操作

作者: 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 表,使用 [] 和 []= 方法,我们实现了线程之间的数据共享。

相关文章

  • 线程的基本操作

    线程的基本操作 •线程状态切换 •终止线程(stop) •中断线程(interrupt) •挂起(suspend)...

  • 线程的基本操作

    线程的创建可以使用Thread.new,Thread.start 或者Thread.fork来创建线程。例如thr...

  • 线程的基本操作

    函数原型 创建线程的函数有四个参数,第一个参数是一个pthread_t类型的指针。第二个参数通常设置为NULL,第...

  • 线程的基本操作

    1.线程中断 线程中断,并不会让线程立即退出,而是给线程发送一个通知,告诉目标线程,有人希望你退出了。至于线程收到...

  • 多线程2:线程的状态转换以及基本操作

    线程的状态转换以及基本操作

  • 线程

    一、Android线程的基本介绍 在操作系统中,线程是操作系统调度的最小单元

  • 线程的状态转换以及基本操作

    线程的状态转换以及基本操作 转载

  • 实战java高并发程序设计第二章(连更)

    1.线程的基本状态2.线程的基本操作3. volatile与java内存模型4.线程组5.守护线程(Daemon)...

  • 理解协程

    一、进程、线程、协程的区别 进程:操作系统中分配资源的基本单位 线程:操作系统中调度资源的基本单位 协程:比线程更...

  • 线程 & 进程

    进程和线程都是操作系统所有的程序运行的基本单元,操作系统利用该基本单元实现操作系统对应用的并发性。 进程和线程的主...

网友评论

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

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