SyncTest类里面有一个同步方法method。新建两个对象:instance1、instance2,它们同时调用method方法。
public class SyncTest {
public synchronized void method() {
System.out.println("Method start");
try {
System.out.println("Method execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method end");
}
public static void main(String[] args) {
final SyncTest instance1 = new SyncTest();
final SyncTest instance2 = new SyncTest();
new Thread(instance1::method).start();
new Thread(instance2::method).start();
}
}
执行结果如下:
Method start
Method execute
Method start
Method execute
Method end
Method end
现象:method方法被两个线程同时调用
结论:在多实例的情况下,同步锁是无效的。synchronized需要单例模式下才有效。
解决:使用单例
public class SyncSingleton {
private static SyncSingleton instance;
public static SyncSingleton getInstance() {
if(instance==null) {
synchronized (SyncSingleton.class) {
if(instance==null) {
instance=new SyncSingleton();
}
}
}
return instance;
}
private SyncSingleton() {}
public synchronized void method() {
System.out.println("Method start");
try {
System.out.println("Method execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method end");
}
}
测试类:
public class SyncSingletonTest {
public static void main(String[] args) {
SyncSingleton instance = SyncSingleton.getInstance();
new Thread(instance::method).start();
new Thread(instance::method).start();
}
}
结果:
Method start
Method execute
Method end
Method start
Method execute
Method end
结论:method方法已经同步执行了。