用信号量semaphore构建有界阻塞容器


package com.cn;

import java.util.*;
import java.util.concurrent.Semaphore;

public class BoundedHashSet<T> {
private final Set<T> set;
private final Semaphore sem;

public BoundedHashSet(int bound){
this.set = Collections.synchronizedSet(new HashSet<T>());
sem = new Semaphore(bound);
}

public boolean add(T o) throws InterruptedException{
sem.acquire();
boolean wasAdded = false;
try{
wasAdded = set.add(o);
return wasAdded;
}finally{
if(!wasAdded){
sem.release();
}
}
}

public boolean remove(Object o){
boolean wasRemoved = set.remove(o);
if(wasRemoved){
sem.release();
}
return wasRemoved;
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
final BoundedHashSet<String> pool = new BoundedHashSet<String>(5);

for(int i = 0; i < 6; i++){
Thread thread = new Thread(new Worker(String.valueOf(i),pool));
thread.start();
}
Thread.currentThread().sleep(2000);
Thread thread = new Thread(new Worker2(String.valueOf(2),pool));
thread.start();
}

}
class Worker implements Runnable{
private final String s ;
final BoundedHashSet<String> pool;
public Worker(String s,BoundedHashSet<String> pool){
this.s = s;
this.pool = pool;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
pool.add(s);
System.out.println("set "+ s);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

class Worker2 implements Runnable{
private final String s ;
final BoundedHashSet<String> pool;
public Worker2(String s,BoundedHashSet<String> pool){
this.s = s;
this.pool = pool;
}
@Override
public void run() {
pool.remove(s);
System.out.println("remove "+ s);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值