Java同步:如果java中的多个方法是原子/同步的,那么锁是否同时应用于所有这些方法?

try*_*arn 0 java multithreading synchronization

假设我的java代码中有2个同步方法:

    public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}
Run Code Online (Sandbox Code Playgroud)

假设我有2个操作线程:t1和t2.如果t1在increment()方法上运行并在中途进入休眠状态,则由于锁定,t2将无法在increment()方法上运行.我的问题是t2能够对decrement()和value()进行操作,或者一旦线程访问其中一个同步方法,与对象关联的所有同步方法都会被锁定吗?

静态同步方法怎么样?

Jon*_*oni 5

同步实例方法使用对象实例作为锁.没有两个线程可以同时使用同一个对象输入这些方法.如果你的t1和t2在同一个对象上运行,t2将被阻塞,直到t1释放锁.

对于静态同步方法,将锁放在Class包含方法的类的对象上.

您可以在并发教程中阅读有关锁定的更多信息,但实质上静态和非静态方法之间的区别在于锁定的对象; 此类中的方法声明:

class Test {
  synchronized void methodA() { ... }
  static synchronized void methodB() { ... }
}
Run Code Online (Sandbox Code Playgroud)

等效于此处的方法声明:

class Test {
  void methodA() { 
    synchronized (this) {
        ...
    }
  }
  static void methodB() { 
    synchronized (Test.class) {
        ...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)