Understand the synchronized keyword in java

Understand the synchronized keyword in java

IT IT haha

1. There are two scopes of the synchronized keyword:

1)是某个对象实例内,synchronized aMethod(){}可以防止多个线程同时访问这个对象的synchronized方法(如果一个对象有多个synchronized方法,只要一个线程访问了其中的一个synchronized方法,其它线程不能同时访问这个对象中任何一个synchronized方法)。这时,不同的对象实例的synchronized方法是不相干扰的。也就是说,其它线程照样可以同时访问相同类的另一个对象实例中的synchronized方法;

2)是某个类的范围,synchronized static aStaticMethod{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。

2. In addition to using the synchronized keyword before the method, the synchronized keyword can also be used in a block in the method, which means that only the resources of this block are mutually exclusive. The usage is: synchronized(this){/ block /}, its scope is the current object;

3. The synchronized keyword cannot be inherited. In other words, the method synchronized f(){} of the base class is not automatically synchronized f(){} in the inherited class, but becomes f(){}. Inherited classes require you to explicitly specify one of its methods as synchronized methods.

Guess you like

Origin blog.51cto.com/15061944/2593720