Maximum Concurrent Threads Allowed

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等类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值