欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-08 08:17:27
...
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);
	}
	
}

相关标签: semaphore set