Java單例模式私有靜態內部類實現並測試
阿新 • • 發佈:2018-12-26
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();
}
}