シングルトン パターンを使用する別の方法は次のとおりです。
4人限定
package org.dixit.amit.immutable;
import java.util.Random;
public class ThreadSafeSingleton {
private ThreadSafeSingleton(){
}
private static ThreadSafeSingleton threadSafeSingleton[] = new ThreadSafeSingleton[3];
static int i = -1;
public static ThreadSafeSingleton getInstance(){
i++;
System.out.println("i is ---> "+i);
if(i<3 && threadSafeSingleton[i]==null){
synchronized (ThreadSafeSingleton.class) {
if(threadSafeSingleton[i]==null){
threadSafeSingleton[i] = new ThreadSafeSingleton();
return threadSafeSingleton[i];
}
}
}
int j = randInt(0, 4);
return threadSafeSingleton[j];
}
private static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}