一種簡單線程併發控制的實現

/**
 * @author 天水
 * @date 2013-4-12 下午05:08:49
 */
public class ConcurrentController implements Runnable {

	// 併發控制數
	private int controlCount;
	// 併發控制超時時間 (second)
	private int controlTimeout;
	// 信號量
	private Semaphore semaphore;
	
	public ConcurrentController(int controlCount, int controlTimeout){
		this.controlCount = controlCount;
		this.controlTimeout = controlTimeout;
		semaphore = new Semaphore(controlCount);
	}
	
	public void run () {
		try {
			if (semaphore.tryAcquire(this.controlTimeout, TimeUnit.SECONDS)) {
				// 業務代碼執行 start
				//Thread.sleep(10);
				System.out.println(String.format("%s - %s run", new Date(), Thread.currentThread()));
				//Thread.sleep(10);
				// 業務代碼執行 end
				semaphore.release();
				return ;
			}else{
				System.out.println(String.format("%s - %s timeout", new Date(), Thread.currentThread()));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args){
		ConcurrentController cc = new ConcurrentController(10, 1);

		// 100 threads
		for(int i=0; i<100; i++){
			new Thread(cc, "Thread - " + i).start();
		}
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章