設計模式學習

1.單例模式:http://www.importnew.com/24272.html html

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.io.FileUtils;

public class TestSingleton {
	private static TestSingleton instance;
    private TestSingleton() {}
    public static TestSingleton getInstance() {
        if (instance == null) {
            try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            instance = new TestSingleton();
        }
        return instance;
    }
    public static void main(String[] args) {
    	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(30);  
		for (int i = 0; i < 50000; i++) {
			final int final_i = i;
			fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println(final_i);
						FileUtils.writeStringToFile(new File("C://TestSingleton.txt"), TestSingleton.getInstance().toString()+"\n",true);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		}
	}
}
test.TestSingleton@7b3a4cdc
test.TestSingleton@5954100e
test.TestSingleton@6e6f83e2
test.TestSingleton@66e1f8f
test.TestSingleton@34469729
test.TestSingleton@5b3ba312
test.TestSingleton@52a7b7ff
test.TestSingleton@284f2189
test.TestSingleton@523e59ca
test.TestSingleton@59628381
test.TestSingleton@199d4a86
test.TestSingleton@766e119d
test.TestSingleton@5b712492
test.TestSingleton@7b7906f4
test.TestSingleton@4769baee
test.TestSingleton@1eb458fd
...

能夠發現不少都不是同一個對象。由此能夠確定這種寫法的單例模式是錯誤的,不安全的。java

 

將上列代碼中的getInstance方法加個synchronized就安全ok了。apache

public static synchronized TestSingleton getInstance() {
        if (instance == null) {
        	try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            instance = new TestSingleton();
        }
        return instance;
    }
相關文章
相關標籤/搜索