ruby是否具有Java的syncnize关键字等效项? [英] Does ruby have the Java equivalent of synchronize keyword?

查看:113
本文介绍了ruby是否具有Java的syncnize关键字等效项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ruby​​是否具有Java的syncnize关键字等效项?我使用的是1.9.1,我看不到一种优雅的方法.

Does ruby have the Java equivalent of synchronize keyword? I am using 1.9.1 and I don't quite see an elegant way to do this.

推荐答案

它没有synchronize关键字,但是可以通过Monitor类获得非常相似的内容.这是《 Ruby编程1.8》一书的一个示例:

It doesn't have the synchronize keyword, but you can get something very similar via the Monitor class. Here's an example from the Programming Ruby 1.8 book:

require 'monitor'

class Counter < Monitor
  attr_reader :count
  def initialize
    @count = 0
    super
  end

  def tick
    synchronize do
      @count += 1
    end
  end
end

c = Counter.new
t1 = Thread.new { 100_000.times { c.tick } }
t2 = Thread.new { 100_000.times { c.tick } }
t1.join; t2.join
c.count → 200000

这篇关于ruby是否具有Java的syncnize关键字等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆