本帖最后由 fjl_fight 于 2013-5-11 00:48 编辑
昨天在论坛看到有人问多线程下的懒汉式单例模式用lock实现的问题,我在那里回答了,为了让更多的人看到,我贴出来分享一下
下面这段代码就不多做解释了。- class Single{
- private static Single s=null;
- private Singleton(){}
- public static Single getInstance(){
- if(s==null){
- synchronized (Single.class) {
- if(s==null){
- s=new Single();
- }
- }
- }
- return s;
- }
- }
复制代码 用Lock实现多线程下的单例(懒汉式)- package test;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- /**
- *
- * @author fjl
- *
- */
- class Single{
- private static Single s=null;
- //构造方法私有化
- private Single(){}
- //创建一个锁对象,由于getInstance()是静态方法,则必须是静态成员该方法才能访问,
- //并将锁声明成final类型,保持该对象不变且只有一个Lock对象
- private static final Lock lock=new ReentrantLock();
- //获得单例实例
- public static Single getInstance(){
- //如果为空
- if(s==null){
- //获取锁
- lock.lock();
- //如果该锁未被其他线程保持(可以查看API),即该锁是空闲的
- if(lock.tryLock()){
- if(s==null){
- //实例化Single对象
- s=new Single();
- }
- }
- }
- //返回
- return s;
- }
- }
- //多线程下测试
- class Test1 implements Runnable{
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while(true){
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(this+"-->"+Single.getInstance());
- }
- }
- }
- //多线程测试
- class Test2 implements Runnable{
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while(true){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- System.out.println(this+"-->"+Single.getInstance());
- }
- }
- }
- public class Demo01 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- // Single s1=Single.getInstance();
- // Single s2=Single.getInstance();
- // System.out.println(s1==s2);
-
- //多线程下测试
- Thread one=new Thread(new Test1());
- Thread one1=new Thread(new Test1());
- Thread one2=new Thread(new Test1());
- Thread two=new Thread(new Test2());
- Thread two1=new Thread(new Test2());
- Thread two2=new Thread(new Test2());
- two.start();
- two1.start();
- two2.start();
- one.start();
- one1.start();
- one2.start();
- }
- }
复制代码 |