Java 单例模式的实现资料整理
Java单例模式的实现,对java单例模式的几种实现方法进行了整理:
单例模式好多书上都是这么写的:
publicclassSingleTon1{ privateSingleTon1(){ } privatestaticSingleTon1instance=null; publicstaticSingleTon1getInstance(){ if(instance==null){ instance=newSingleTon1(); } returninstance; } }
但是实际开发中是不会这么写的,因为有一个严重的问题,多线程并发访问的时候,可能会产生多个实例!!
下面列举几个常用的方法:
1.使用synchronized关键字
packagesingleton; publicclassSingleTon1{ privateSingleTon1(){ } privatestaticSingleTon1instance=null; //多线程问题解法一,但是效率不高!因为每次调用都会加锁! publicstaticsynchronizedSingleTon1getInstance(){ if(instance==null){ instance=newSingleTon1(); } returninstance; } publicvoidprint(){ System.out.println("thread_id:"+Thread.currentThread().getId()); } privatestaticObjectobject=newObject(); //很巧妙的方法,只有在null的时候加锁,之后就不加啦 publicstaticSingleTon1getInstance2(){ if(instance==null){ synchronized(object){ instance=newSingleTon1(); } } returninstance; } }
2.加锁
packagesingleton; importjava.util.concurrent.locks.ReentrantLock; publicclassSingleTon2{ privateSingleTon2(){ } privatestaticReentrantLocklock=newReentrantLock(); privatestaticSingleTon2instance=null; publicvoidprint(){ System.out.println("thread_id:"+Thread.currentThread().getId()); } publicstaticSingleTon2getInstance2(){ if(instance==null){ lock.lock(); if(instance==null){//注意这里还要判断下!! instance=newSingleTon2(); } lock.unlock(); } returninstance; } }
3.利用静态变量:
packagesingleton; publicclassSingleTon3{ publicstaticvoidprint(){ System.out.println("thread_id:"+Thread.currentThread().getId()); } publicstaticNestedgetNested(){ returnNested.instance; } //这个是单例创建的类 staticclassNested{ privateNested(){ } staticNestedinstance=newNested(); } }
以上就是常用的创建单例的模式:
Test测试代码:
packagesingleton; importsingleton.SingleTon3.Nested; publicclassTest2{ publicstaticvoidmain(String[]args){ //TODOAuto-generatedmethodstub Nestedsingleton; Myrunnablemm=newMyrunnable(); Myrunnablem1=newMyrunnable(); Myrunnable2m2=newMyrunnable2(); newThread(m1).start(); newThread(m2).start(); if(m1.singleton==m2.singleton){//是同一个 System.out.println("是同一个"); }else{ System.out.println("不是同一个"); } } } classMyrunnableimplementsRunnable{ Nestedsingleton; @Override publicvoidrun(){ //TODOAuto-generatedmethodstub singleton=SingleTon3.getNested(); SingleTon3.print(); } } classMyrunnable2implementsRunnable{ Nestedsingleton; @Override publicvoidrun(){ //TODOAuto-generatedmethodstub singleton=SingleTon3.getNested(); SingleTon3.print(); } }
输出:
是同一个
thread_id:11
thread_id:10
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!