一、好言
最好的生活状态不过就是:一个人,安静而丰盛;两个人,温暖而踏实。
二、背景
看《Java并发编程实战》,第五章,代码练习记载下
三、内容
package com.mouse.moon.threaddemo;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;
/**
* Created by Mahone Wu on 2017/6/16.
*/
public class BoundHashSet<T> {
private final Set<T> set ;
private final Semaphore semaphore;
public BoundHashSet(int bound){
this.set = Collections.synchronizedSet(new HashSet<T>());
semaphore = new Semaphore(bound);
}
public boolean add(T o) throws InterruptedException{
semaphore.acquire();//获取许可
boolean wasAdd = false;
try {
wasAdd = set.add(o);
return wasAdd;
}finally {
if(!wasAdd){
semaphore.release();
}
}
}
public boolean remove(Object o){
boolean wasRemoved = set.remove(o);
if(wasRemoved){
semaphore.release();//释放许可
}
return wasRemoved;
}
}
package com.mouse.moon.threaddemo;
/**
* Created by Mahone Wu on 2017/6/16.
*/
public class Person {
private String name;
private String address;
public Person(String name, String address) {
this.name = name;
this.address = address;
}
}
package com.mouse.moon.threaddemo;
/**
* Created by Mahone Wu on 2017/6/16.
*/
public class Main {
public static void main(String[] args) {
final Integer permit = 3;
Person p1 = new Person("a", "a");
Person p2 = new Person("b", "b");
Person p3 = new Person("c", "c");
Person p4 = new Person("d", "d");
Person p5 = new Person("e", "e");
BoundHashSet bhs = new BoundHashSet(permit);
boolean f1 = false;
try {
f1 = bhs.add(p1);
} catch (InterruptedException e) {
System.out.println("1");
e.printStackTrace();
}
System.out.println(f1);
boolean f2 = false;
try {
bhs.remove(p1);//这里释放,可以自动修改许可permit大小
f2 = bhs.add(p2);
} catch (InterruptedException e) {
System.out.println("2");
e.printStackTrace();
}
System.out.println(f2);
boolean f3 = false;
try {
f3 = bhs.add(p3);
} catch (InterruptedException e) {
System.out.println("3");
e.printStackTrace();
}
System.out.println(f3);
boolean f4 = false;
try {
f4 = bhs.add(p4);
} catch (InterruptedException e) {
System.out.println("4");
e.printStackTrace();
}
System.out.println(f4);
boolean f5 = false;
try {
f5 = bhs.add(p5);
} catch (InterruptedException e) {
System.out.println("5");
e.printStackTrace();
}
System.out.println(f5);
}
}
可以看见打印了4个true,并且程序还处理执行中,等待释放一直阻塞到有为至。