单例和同步锁

 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方法已经同步执行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值