java synchronized方法 - 它是如何工作的 [英] java synchronized method - how does it work

查看:110
本文介绍了java synchronized方法 - 它是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我知道这一点,但希望确认一下。

I think I know this, but would like it confirming.

显然,synchronized会阻止其他线程访问它,但是我看到了很多例子,比如

Obviously the synchronized blocks other threads from accessing it, but I see and awful lot of examples such as

   public synchronized void setValue(int value)
   {
       balance=value;
   }

我是否正确地想,如果方法只做一行像在上面,它没有任何意义同步。

Am I right in thinking, that if the method only does one line like the above, then there is no point in it being synchronized.

谢谢

推荐答案


我是否正确地思考,如果该方法只执行如上所述的一行,那么它就没有任何意义同步。

Am I right in thinking, that if the method only does one line like the above, then there is no point in it being synchronized.

没有。你似乎相信同步只意味着原子性。

No. You seem to believe that synchronized only means atomicity.

但它实际上提供了更多 - 特别是,它保证:

But it actually provides more than that - in particular, it guarantees:


  • 原子性,对单行分配无用(下面的边框除外)

  • 可见性

  • 阻止重新排序

  • 互斥:在同一台显示器上同步的2种方法无法同时运行

  • atomicity, which is not useful for a one line assigment (except in border case below)
  • visibility
  • prevents reordering
  • mutual exclusion: 2 methods synchronized on the same monitor can't be run concurrently

在您的示例中,如果没有同步,则无法保证如果某个线程调用您的方法而另一个线程随后读取 balance ,则该第二个线程将看到更新的值。

In your example, without synchronized, you have no guarantee that if a thread calls your method and another reads balance subsequently, that second thread will see the updated value.

请注意,必须在两端确保可见性:写入和读取需要与同一监视器同步。所以getter getBalance 也需要syhcnronized。

Note that visibility must be ensured at both ends: the write AND the read need to be synchronized, with the same monitor. So the getter getBalance will need to be syhcnronized too.

边境案例:< a href =http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7>不能保证双重和长期分配是原子的。因此,即使在如下所示的单行示例中,如果没有synchronized关键字,也有可能一个线程更新double的前32位而另一个线程更新最后32位,从而创建一个新的混合平衡变量。

Border case: double and long assignements are not guaranteed to be atomic. So even on a one line example like below, without the synchronized keyword, it would be possible that one thread updates the first 32 bits of the double and another thread updates the last 32 bits, creating a new mixed up balance variable.

public synchronized void setValue(double value) {
    balance = value;
}

这篇关于java synchronized方法 - 它是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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