Java單例模式私有靜態內部類實現並測試

package org.vincent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 單例模式實現,靜態私有類實現。
 * @author  pengrong
 *
 */
public class Singleton {
    private Singleton() {
    };
    public static Singleton getInstance() {
        return Holder.instance;
    }
    private static class Holder{
        private volatile static Singleton instance = new Singleton();
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException { 
        ExecutorService executorService=Executors.newCachedThreadPool();
        for (int i = 0; i < 10000; i++) {
            Future<Integer> future=executorService.submit(new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {

                    return Singleton.getInstance().hashCode();
                }
            });
            System.out.println("第 "+(i+1)+" 個"+future.get());;
        }
        executorService.shutdown();
    }
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章