您的位置:首页 > 其它

一种简单线程并发控制的实现

2013-04-12 18:18 239 查看
/**
* @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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: