Singleton,了解一下

package suanfa;

import java.util.concurrent.locks.ReentrantLock;

public class MySingleton {
    static class S1 {
        private static S1 instance;
        private S1() {
        }


        public static S1 getInstance() {
            if (instance == null) {
                instance = new S1();
            }
            return instance;
        }
    }

    static class S2 {
        private static S2 instance;
        public S2() {
        }
        public static synchronized S2 getInstance() {
            if (instance == null) {
                instance = new S2();

            }
            return instance;
        }
    }


    static class S3 {
        private static S3 instance;
        private static byte[] lock  = new byte[0];
        private S3() {
        }

        public static S3 getInstance() {
            if (instance == null) {
                synchronized (lock) {
                    if (instance == null) {
                        instance = new S3();
                    }

                }
            }
            return instance;
        }
    }


    static class S4 {
        private static S4 instance; 
        private static ReentrantLock lock = new ReentrantLock();
        private S4() {
        }

        public static S4 getInstance() {
            if (instance == null) {
                lock.lock();
                if (instance==null) {
                    instance = new S4();
                }
                lock.unlock();
            }
            return instance;
        }
    }


}

猜你喜欢

转载自blog.csdn.net/java_sparrow/article/details/81226093