Java中的线程和同步

shr*_*sva 3 java multithreading

如果类中有synchronized方法并且1个线程进入它,则另一个线程可以在不同的对象上调用相同的方法.

Joa*_*uer 7

是的,如果方法不是static.

synchronized非静态方法同步上this.所以这个方法:

public synchronized void foo() {
  // do stuff
}
Run Code Online (Sandbox Code Playgroud)

实际上相当于这个:

public void foo() {
  synchronized(this) {
    // do stuff
  }
}
Run Code Online (Sandbox Code Playgroud)

static同步方法同步于当前类.所以像这样的方法:

public static synchronized void bar() {
  // do stuff
}
Run Code Online (Sandbox Code Playgroud)

实际上相当于这个:

public static void bar() {
  synchronized(ThisClass.class) {
    // do stuff
  }
}
Run Code Online (Sandbox Code Playgroud)