JAVA并发编程实践 83页
JAVA信号量实际用的并不多,书上的例子记录一下。
若许可证不足,则线程阻塞
-
import java.util.*;
-
import java.util.concurrent.*;
-
-
public class BoundedHashSet<T>{
-
private final Set<T> set;
-
private final Semaphore sem;
-
-
public BoundedHashSet(int bound){
-
this.set=Collections.synchronizedSet(new HashSet<T>());
-
this.sem=new Semaphore(bound);
-
}
-
-
public void add(T o) throws InterruptedException{
-
sem.acquire();
-
set.add(o);
-
System.out.println("add"+o);
-
}
-
-
public void remove(T o) {
-
set.remove(o);
-
sem.release();
-
}
-
-
public static void main(String[] args) throws InterruptedException
-
{
-
BoundedHashSet<Integer> set=new BoundedHashSet<Integer>(3);
-
set.add(1);
-
set.add(2);
-
set.add(3);
-
set.add(4);
-
}
-
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1164711/
,如需转载,请注明出处,否则将追究法律责任。