0 java singleton multithreading
我有一个使用单例模式的程序.我需要使用它的线程,记住在使用线程机械化之前和之后输出应该是相同的.我的意思是避免"破碎模式"的情况,其中线程忽略单例并创建更多的一个对象.但是,我失败了.我试图使用"同步",但没有任何改变.同样错误的结果.
我主要用Runnable
    public class Main implements Runnable  {
    Main(){}
    public void run ()
        { 
            Counter[] counters = new Counter[5];
            for(int i = 0; i < counters.length; i++) 
                {
                    counters[i] = Counter.getCounter();
                }
            for(int i = 0; i < counters.length; i++) 
                {
                    counters[i].increment();
                    System.out.println("counter[" + i + "] = " + counters[i]);
                }
            for(int i = 0; i < 5; i++) {
                counters[i].decrement();
                System.out.println("counter[" + i + "] = " + counters[i]);
                }}
    public static void main(String[] args)  
    {
        Main m1=new Main();
        Main m2=new Main();
        Main m3=new Main();
        new Thread(m1).start();
        new Thread(m2).start();
        new Thread(m3).start(); 
    }
}
另一个应用单例模式的类
 public  class Counter {
        private static Counter myInstance = null;
        public static  Counter getCounter() 
        {
            if(myInstance == null) 
                {
                    synchronized (Counter.class)                    {
                        if(myInstance == null) 
                        {
                            myInstance = new Counter();
                        }
                    }   
                }
        return(myInstance);
        }
        private int myCounter;
        private Counter() {
        myCounter = 0;
        }
        public void increment() {
        myCounter++;
        }
        public void decrement() {
        myCounter--;
        }
        public String toString() {
        return(Integer.toString(myCounter));
        }
    }
不要使用双重检查的单一模式,它不是现代的方式,无论它是否破碎.
Java中的单例应该使用内部类或枚举来实现(请参阅Effective Java Item 3:使用私有构造函数或枚举类型强制执行singleton属性):
a)内部类单身人士模式:
public class MySingleton{
    private MySingleton(){}
    private static class InstanceHolder{
        private static final MySingleton INSTANCE = new MySingleton(); 
    }
    public static MySingleton getInstance(){
        return InstanceHolder.INSTANCE;
    }
}
b)枚举单例模式
public enum MySingleton{
    INSTANCE;
    public static MySingleton getInstance(){
        return INSTANCE;
    }
}