正如SO answer 准确指出的那样
there is no link between synchronized static methods and sync'ed non static methods in
this context
为了证明这一点。
public class SimpleClassTest {
静态同步方式
public static synchronized void X1() {
System.out.println("Before X1 Exec.. From"+Thread.currentThread().getName());
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("After X1 Exec.. From"+Thread.currentThread().getName());
}
非静态同步方法
public synchronized void X2() {
System.out.println(" X2 Exec.. From"+Thread.currentThread().getName());
}
第一种方法只是休眠一段时间然后醒来。
第二种方法同步但不是静态的。
现在尝试创建两个线程并同时调用这个方法(大约)
public static void main(String args[]){
final SimpleClassTest instance = new SimpleClassTest();
静态的第一个线程
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
SimpleClassTest.X1();
}
},"Thread1");
非静态的第二个线程
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
instance.X2();
}
},"Thread2");
现在启动两个线程
t1.start();
t2.start();
结果
Before X1 Exec.. FromThread1
X2 Exec.. FromThread2
After X1 Exec.. FromThread1
从结果来看,两个线程运行时没有相互锁定。因为如果第一个线程锁定了第二个线程锁定的同一个对象,那么线程 2 将等待第一个线程完成。
因此,我们确信两者都是并行运行的。
第一个线程锁定了 SimpleClasstest.class,因为它是与实例无关的静态方法。
第二个线程锁定实例,因为它是非静态的。
希望可以解决