编程语言
首页 > 编程语言> > java 单例(Singleton)、多例(Multiton)、复杂多例(MultitonPool)、多例线程池(MultitonThreadPool)

java 单例(Singleton)、多例(Multiton)、复杂多例(MultitonPool)、多例线程池(MultitonThreadPool)

作者:互联网

通过7个例子展示单例、多例、多例线程池方式

  1. SingletonPatternDemo 主程序
package com.myibs.test.service.singleAndMultiTon;

import java.util.HashMap;
import java.util.Objects;

public class SingletonPatternDemo {

    public static void main(String[] args) {

        //Test 1: 不合法的构造函数
        //编译时错误:构造函数 SingleObject() 是private/不可见的
        //SingleObject object = new SingleObject();

        //Test 2:单例模式(饿汉模式)
        //此项是基础测试
        Singleton object2 = Singleton.getInstance();
        //显示消息
        object2.showMessage();
        object2.setsStr("2");
        object2.showMessage();

        Singleton object21 = Singleton.getInstance();
        object21.setsStr("3");  /**由于大家共享一个变量,这个就是要命的地方了*/
        object2.showMessage();
        object21.showMessage();
        if (object2 == object21) {
            System.out.println("These two objects are the same");
        }
        if (object2.equals(object21)) {
            System.out.println("These two objects are the same");
        }
        if (Objects.equals(object2,object21)) {
            System.out.println("These two objects are the same");
        }

        //Test 3:单例模式(Lazy)
        //此项是基础测试
        SingletonLazy object3 = SingletonLazy.getInstance();
        //显示消息
        object3.showMessage();
        object3.setsStr("2");
        object3.showMessage();

        //关键是这里,再去建立的时候就直接返回之前的单例了,返回值就是2
        SingletonLazy object1 = SingletonLazy.getInstance();
        object1.showMessage();
        object3.setsStr("3");
        object1.showMessage();   //由于大家共享一个变量,这个就是要命的地方了
        if (object1 == object3) {
            System.out.println("These two objects are the same");
        }
        if (object3.equals(object1)) {
            System.out.println("These two objects are the same");
        }
        if (Objects.equals(object1,object3)) {
            System.out.println("These two objects are the same");
        }

        //Test 4:看看是否能通过单例模式获取多个不同多线程对象,结果是不可以
        SingletonThread objectThread1 = SingletonThread.getInstance();
        SingletonThread objectThread2 = SingletonThread.getInstance();
        SingletonThread objectThread3 = SingletonThread.getInstance();

        objectThread1.setName1("111");
        objectThread2.setName1("222");
        objectThread3.setName1("333");
        System.out.println(objectThread1 + "|" + objectThread1.hashCode() + "|" + System.identityHashCode(objectThread1));
        System.out.println(objectThread2 + "|" + objectThread2.hashCode() + "|" + System.identityHashCode(objectThread2));
        System.out.println(objectThread3 + "|" + objectThread3.hashCode() + "|" + System.identityHashCode(objectThread3));
        objectThread1.showMessage();
        objectThread2.showMessage();
        objectThread3.showMessage();

        try {
            objectThread1.start();  /** 代码在此处正常*/
            objectThread2.start();  /** Thread Exception,因为无法在此Object上继续new thread*/
            objectThread3.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Test 5:简单多例模式
        SimpleMultiton multi1;
        SimpleMultiton multi2;
        multi1 = SimpleMultiton.getInstance(1);
        multi2 = SimpleMultiton.getInstance(2);
        System.out.println(multi1.getValue());
        System.out.println(multi2.getValue());

        System.out.println(multi1 + "|" + multi1.hashCode() + "|" + System.identityHashCode(multi1));
        System.out.println(multi2 + "|" + multi2.hashCode() + "|" + System.identityHashCode(multi2));

        if (multi1 == multi2) {
            System.out.println("These two objects are the same");
        } else {
            System.out.println("These two objects are not the same");
        }

        if (multi1.equals(multi2)) {
            System.out.println("These two objects are the same");
        }else {
            System.out.println("These two objects are not the same");
        }

        if (Objects.equals(multi1,multi2)) {
            System.out.println("These two objects are the same");
        }else {
            System.out.println("These two objects are not the same");
        }

        //Test 6:复杂多例模式/多例池
        try {
            MultitonPool multitonPool1;
            MultitonPool multitonPool2;
            MultitonPool.init(2);  
            multitonPool1 = MultitonPool.getInstance(0);
            multitonPool2 = MultitonPool.getInstance(1);
            System.out.println(multitonPool1.getValue());
            System.out.println(multitonPool2.getValue());

            HashMap<Integer, MultitonPool> multitonPoolMap = MultitonPool.getInstance();
            Integer loop = 0;
            for (Object o :multitonPoolMap.keySet()) {
                MultitonPool Multiton = (MultitonPool)multitonPoolMap.get(loop);
                System.out.println(Multiton.getValue());
                loop++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        //Test 7:多例线程池
        try {
            MultitonThreadPool multitonThreadPool1;
            MultitonThreadPool multitonThreadPool2;
            MultitonThreadPool.init(2);  //告诉多例,线程池建立的上限是2个
            MultitonThreadPool.init(2); //应该直接退出,防止重复建立
            multitonThreadPool1 = MultitonThreadPool.getInstance(0);
            multitonThreadPool2 = MultitonThreadPool.getInstance(1);
            System.out.println(multitonThreadPool1.getValue());
            System.out.println(multitonThreadPool2.getValue());

            //根据线程数依次启动线程池中的线程
            HashMap<Integer, MultitonThreadPool> multitonThreadMap = MultitonThreadPool.getInstance();
            Integer loop = 0;
            for (Object o :multitonThreadMap.keySet()) {
                MultitonThreadPool multitonThread = (MultitonThreadPool)multitonThreadMap.get(loop);
                System.out.println(multitonThread.getValue());
                multitonThread.start();
                loop++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

  1. MultitonPool
package com.myibs.test.service.singleAndMultiTon;

import java.util.HashMap;

/**
 * @author user
 */
public class MultitonPool {
    private static HashMap<Integer, MultitonPool> advancedMultitonMap = new HashMap<>();
    private static MultitonPool advancedMultiton = new MultitonPool();

    private MultitonPool() {

    }

    public static void init(Integer numberOfInstance) {
        for (int loop = 0; loop < numberOfInstance; loop++) {
            MultitonPool advancedMultiton = new MultitonPool();
            advancedMultitonMap.put(loop,advancedMultiton);
        }
    }

    /**
     * 一定要申明为静态类,这样才能穿透直接获取,通过自己管自己: static Singleton instance = new Singleton();
     */
    public static MultitonPool getInstance(Integer instanceId) {
        return (MultitonPool)advancedMultitonMap.get(instanceId);
    }

    /**
     * 一定要申明为静态类,这样才能穿透直接获取,通过自己管自己: static Singleton instance = new Singleton();
     */
    public static HashMap getInstance() {
        return advancedMultitonMap;
    }

    /**
     * 获取1—6之间的随机数
     */
    public int getValue() {
        System.out.println(this + "|" + this.hashCode() + "|" + System.identityHashCode(this));
        int value = (int)(Math.random()*6+1);
        return value;
    }
}

  1. MultitonThreadPool
package com.myibs.test.service.singleAndMultiTon;

import java.util.HashMap;

/**
 * @author user
 */
public class MultitonThreadPool extends Thread {
    private static HashMap<Integer, MultitonThreadPool> advancedMultitonMap = new HashMap<>();
    private static MultitonThreadPool advancedMultiton = new MultitonThreadPool();
    private int value;

    private MultitonThreadPool() {

    }

    public static void init(Integer numberOfInstance) {
        //如果发现已初始化,退出。防止反复调用
        if (advancedMultitonMap.isEmpty() == false) {
            return;
        }

        for (int loop = 0; loop < numberOfInstance; loop++) {
            MultitonThreadPool advancedMultiton = new MultitonThreadPool();
            advancedMultiton.setValue(loop);
            advancedMultitonMap.put(loop,advancedMultiton);
        }
    }

    /**
     * 一定要申明为静态类,这样才能穿透直接获取,通过自己管自己: static Singleton instance = new Singleton();
     */
    public static MultitonThreadPool getInstance(Integer instanceId) {
        return (MultitonThreadPool)advancedMultitonMap.get(instanceId);
    }

    /**
     * 一定要申明为静态类,这样才能穿透直接获取,通过自己管自己: static Singleton instance = new Singleton();
     */
    public static HashMap getInstance() {
        return advancedMultitonMap;
    }

    /**
     * 获取1—6之间的随机数
     */
    public int getValue() {
        System.out.println(this + "|" + this.hashCode() + "|" + System.identityHashCode(this));
        //value = (int)(Math.random()*6+1);  //Math.random 线程不安全,避免使用
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(100);
            for (int i = 0; i < 10; i++) {
                System.out.println("Thread pool: " + value + ": 运行,i = " + i);
            }
        } catch (InterruptedException e) {
            System.out.println("Thread pool: " + value +": Thread is terminated.....");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

  1. SimpleMultiton
package com.myibs.test.service.singleAndMultiTon;

/**
 * @author user
 */
public class SimpleMultiton {
    private static SimpleMultiton multi1 = new SimpleMultiton();
    private static SimpleMultiton multi2 = new SimpleMultiton();

    private SimpleMultiton() {}

    /**
     * 一定要申明为静态类,这样才能穿透直接获取,通过自己管自己: static Singleton instance = new Singleton();
     */
    public static SimpleMultiton getInstance(int key) {
        if(key == 1) {
            return multi1;
        } else {
            return multi2;
        }
    }

    /**
     * 获取1—6之间的随机数
     */
    public int getValue() {
        int value = (int)(Math.random()*6+1);
        return value;
    }
}

  1. Singleton
package com.myibs.test.service.singleAndMultiTon;

/**
 *获取唯一可用的对象,恶汉式。来了照单全收,全部创建,浪费资源
 */
public class Singleton {

    public String getsStr() {
        return sStr;
    }

    public void setsStr(String sStr) {
        this.sStr = sStr;
    }

    /**
     * 记得哦,初始化时是 1, 事后通过代码来修改的
     */
    private String sStr="1";

    //创建 SingleObject 的一个对象
    private static Singleton instance = new Singleton();

    /**
     * 记让构造函数为 private,这样该类就无法通过外部被实例化
     */
    private Singleton(){
        System.out.println("SingleObject construction");
    }

    /**
     * 获取唯一可用的对象,饿汉式
     * 一定要申明为静态类,这样才能穿透直接获取,通过自己管自己: static Singleton instance = new Singleton();
     */
    public static Singleton getInstance(){
        return instance;
    }

    public void showMessage(){
        System.out.println("Hello World! " + sStr);
    }

}

  1. SingletonLazy
package com.myibs.test.service.singleAndMultiTon;

public class SingletonLazy {

    public String getsStr() {
        return sStr;
    }

    public void setsStr(String sStr) {
        this.sStr = sStr;
    }

    private String sStr="1";

    //创建 SingleObject 的一个对象
    private static SingletonLazy instance = new SingletonLazy();

    //让构造函数为 private,这样该类就无法通过外部被实例化
    private SingletonLazy(){}

    //使用Synchronized方式锁定,获取唯一可用的对象
    public static synchronized SingletonLazy getInstance(){
        if (instance == null) {
            instance = new SingletonLazy();
        }
        return instance;
    }

    public void showMessage(){
        System.out.println("Hello World! " + sStr);
    }

}

  1. SingletonThread
package com.myibs.test.service.singleAndMultiTon;

public class SingletonThread extends Thread {

    public String getName1() {
        return name1;
    }

    public void setName1(String name1) {
        this.name1 = name1;
    }

    String name1;

    //创建 SingleObject 的一个对象
    private static SingletonThread instance = new SingletonThread();

    //让构造函数为 private,这样该类就无法通过外部被实例化
    private SingletonThread(){}

    //获取唯一可用的对象
    public static SingletonThread getInstance(){
        return instance;
    }

    public void showMessage(){
        System.out.println("Hello World!: " + name1 );
    }

    @Override
    public void run() {
        try {
            Thread.sleep(100);
            for (int i = 0; i < 10; i++) {
                System.out.println(name1 + ": 运行,i = " + i);
            }
        } catch (InterruptedException e) {
            System.out.println(name1 +" Thread is terminated.....");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

标签:MultitonPool,Singleton,getInstance,多例,System,static,println,public,out
来源: https://blog.csdn.net/snetlogon20/article/details/111879632