神奇好望角 The Magical Cape of Good Hope

庸人不必自扰,智者何需千虑?
posts - 26, comments - 50, trackbacks - 0, articles - 11
  BlogJava :: 首页 ::  :: 联系 :: 聚合  :: 管理
我对 Java 关键字 Synchronized 的新理解 My New Understanding of Java's Synchronized Keyword
  说实话,我对 Java 并发编程知之不多。我曾经常用关键字 volatile 试图“强制原子操作”,结果带来的麻烦比解决的还多。Sun Java 教程中的并发课程我以前从没看完过,现在该通读一遍了。     To be honest, I knew only a little about concurrent programming in Java. I uesed to use keyword volatile as an attempt to "enforce atomic operations" which had brought me more troubles than solved. Time to walk through the Concurrency Trail of Sun's Java Tutorials that I never finished reading in the past.
  我其实知道并经常看到关键字 synchronized 的使用,但直到昨天我还没发觉就这个字消除了很多同步问题。然而,真正的答案在我第一次看这个教程时就在里面了,到这次才弄清。     I do know and often see the usage of keyword synchronized, but until yesterday I hadn't figured out how thie single word elimated so many synchronization problems. However, the very answer lies in those tutorials ever since I first read it and this time it has been clearly understood.
  每个对象都关联有一个内部锁,也被称作监视器锁或简称监视器。当一个线程调用一个同步方法时,它自动请求此方法的内部锁,并在方法返回时释放。即使是未捕获的异常造成了返回,也会发生锁的释放。而对静态同步方法,方法所在类的 Class 对象的内部锁被请求。同步语句的内部行为没什么两样,只是还需要显示指定一个需要请求其内部锁的任意对象。

    Every boject has an intrinsic lock, which is also known as monitor lock or monitor for short, associated with it. When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception. As for a static synchronized method, an intrinsic lock for the Class object of that method's Class is acquired instead. Synchronized statements internally behaves no differently except in addition to this, an arbitrary object whose intrinsic lock will be acquired can be and should be explicitly specified.

  总之,synchronized 关键字是锁定对象的简单方式,也有很多局限。java.util.concurrency.locks 包支持更高深的锁定用法,也是我将要学的。

    In conclusion, synchronized keyword is a simplified way of locking objects, and also has many limitations. More sophisticated locking idioms are supported by the java.util.concurrency.locks package which I am going to learn.


只有注册用户登录后才能发表评论。


网站导航: