Semaphore线程并发

阅读更多
Semaphore 信号量-多线程:限制线程并发的数量

//过独木桥
public class GBridge {

private Semaphore sem = new Semaphore(1);

//只有一个线程能调用该方法
public void come(){
try{
sem.acquire();
System.out.println(Thread.currentThread().getName()+new Date());
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
sem.release();
}
}

public static void main(String args[]){
GBridge bridge = new GBridge();

for(int i=0;i<10;i++){
Thread person1 = new Person(bridge);
person1.start();
}
}

static class Person extends Thread{
private GBridge bridge;

public Person(GBridge bridge){
this.bridge = bridge;
}

public void run() {
bridge.come();
}
}
}

处理超时:boolean b =sem.tryAcquire(3000, TimeUnit.MILLISECONDS);
在3秒内返回true,超时返回false


你可能感兴趣的:(多线程)