public class Test {
private static PersistenceManager instance = new PersistenceManager();
private static volatile int threadCounter = 0;
// maximum concurrent threads allowed
private static int N = 3;
public static void rockNroll() {
PersistenceManager instance;
while(threadCounter >= N) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
if(threadCounter < N) {
getAndAdd(1);
System.out.println("current working threads is " + threadCounter);
instance = doWork();
getAndAdd(-1);
} else {
instance = null;
}
if(instance != null) {
System.out.println("well done...");
}
}
private static PersistenceManager doWork() {
return getPMInstance();
}
private static synchronized void getAndAdd(int delta) {
threadCounter += delta;
}
public static PersistenceManager getPMInstance() {
return instance;
}
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
new Thread() {
public void run() {
rockNroll();
}
}.start();
}
}
}
class PersistenceManager {
}
因为涉及Google App Engine,因此不能用ReentrantLock, AtomicInteger等类