The difference between synchronized and static synchronized in JAVA

The difference between synchronized and static synchronized in JAVA

IT IT haha

1. The difference between synchronized and static synchronized

    synchronized是对类的当前实例进行加锁,防止其他线程同时访问该类的该实例的所有synchronized块,注意这里是“类的当前实例”, 类的两个不同实例就没有这种约束了。那么static synchronized恰好就是要控制类的所有实例的访问了,static synchronized是限制线程同时访问jvm中该类的所有实例同时访问对应的代码快。实际上,在类中某方法或某代码块中有 synchronized,那么在生成一个该类实例后,改类也就有一个监视快,放置线程并发访问改实例synchronized保护快,而static synchronized则是所有该类的实例公用一个监视快了,也也就是两个的区别了,也就是synchronized相当于 this.synchronized,而static synchronized相当于Something.synchronized.
     一个日本作者-结成浩的《java多线程设计模式》有这样的一个列子:

pulbic class Something(){ 
    publicsynchronizedvoid isSyncA(){} 
    publicsynchronizedvoid isSyncB(){} 
    publicstaticsynchronizedvoid cSyncA(){} 
    publicstaticsynchronizedvoid cSyncB(){} 
} 
   那么,加入有Something类的两个实例a与b,那么下列组方法何以被1个以上线程同时访问呢

a. x.isSyncA()与x.isSyncB()  
b. x.isSyncA()与y.isSyncA() 
c. x.cSyncA()与y.cSyncB() 
d. x.isSyncA()与Something.cSyncA() 

Here, it is clear that you can judge:
a, are all accesses to the synchronized domain of the same instance, so they cannot be accessed at the same time. b is for different instances, so they can be accessed at the same time c. Because it is static synchronized, different instances of The time will still be restricted, which is equivalent to Something.isSyncA() and Something.isSyncB(), so they cannot be accessed at the same time. So, what about the d? The answer in the book can be accessed at the same time. The reason for the answer is that the instance method of synchronzied is different from the class method of synchronzied due to the different reasons of lock. Personal analysis is that synchronized and static synchronized are equivalent to two gangs, each manages its own, and there is no restriction between each other and can be accessed at the same time. It is not yet clear how the internal design of synchronzied in java is realized.

Conclusion: A: synchronized static is the scope of a certain class, synchronized static cSync{} prevents multiple threads from simultaneously accessing synchronized static methods in this class. It can act on all object instances of the class.
B: synchronized is the scope of an instance, synchronized isSync(){} prevents multiple threads from simultaneously accessing the synchronized method in this instance.

2. The difference between synchronized method and synchronized code fast

    synchronized methods(){} 与synchronized(this){}之间没有什么区别,只是synchronized methods(){} 便于阅读理解,而synchronized(this){}可以更精确的控制冲突限制访问区域,有时候表现更高效率。

3. The synchronized keyword cannot be inherited

     这个在《搞懂java中的synchronized关键字》一文中看到的,我想这一点也是很值得注意的,继承时子类的覆盖方法必须显示定义成synchronized。(但是如果使用继承开发环境的话,会默认加上synchronized关键字)

Guess you like

Origin blog.51cto.com/15061944/2593721