synchronized 关键字

修饰成员方法,是对象级别的同步

class X {
    private int a;
    private int b;
    public synchronized void addA(){
        a++;
    }
    public synchronized void addB(){
        b++;
    }
}

Syncronized on the method declaration is syntactical sugar for this:

 public void addA() {
     syncronized (this) {
          a++;
     }
  }

修饰静态方法,是类级别的同步

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.

修饰某个对象

但是只能修饰引用。对于像 int 的原生型不能这样修饰。可以用 AtomicInteger。像这样

import java.util.concurrent.atomic.AtomicInteger;
class X {
    AtomicInteger a;
    AtomicInteger b;
    public void addA() {
        a.incrementAndGet();
    }
    public void addB() {
        b.incrementAndGet();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容