1.修饰一个方法

被修饰的方法称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象;

synchronized关键字不属于方法定义的一部分,所以不能继承。

public synchronized void method() {
}

// 等价于

public void method() { synchronized (this) { } }

 

2.修饰代码块

线程进入则得到括号内的对象锁,其他线程需等待。

final Object mutex;
public int size() {
            synchronized (mutex) {return 0;}
}

 

相关文章:

  • 2021-06-18
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2021-05-22
  • 2021-09-03
猜你喜欢
  • 2022-12-23
  • 2022-03-05
  • 2022-12-23
相关资源
相似解决方案