package projects.debug.learn;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.Semaphore;
public class SyncQueue implements Queue
{
private final Queue mQueue;
private final int mCapacity;
private final Semaphore mSemProducer;
private final Semaphore mSemConsumer;
public SyncQueue(Queue queue)
{
this(queue, Integer.MAX_VALUE);
}
public SyncQueue(Queue queue, int capacity)
{
mQueue = queue;
mCapacity = capacity;
mSemProducer = new Semaphore(capacity);
mSemConsumer = new Semaphore(0);
}
public Object get()
{
// Accquire consumer's semaphore
try
{
mSemConsumer.acquire();
}
catch(InterruptedException ie)
{
Thread.currentThread().interrupt();
return null;
}
// Get the item
Object item = null;
synchronized(mQueue)
{
item = mQueue.poll();
}
//
mSemProducer.release();
return item;
}
public boolean put(Object item)
{
// Precondition checking
if(item == null)
{
return false;
}
// Accquire producer's semaphore
try
{
mSemProducer.acquire();
}
catch(InterruptedException ie)
{
Thread.currentThread().interrupt();
return false;
}
// Add the item
synchronized(mQueue)
{
mQueue.add(item);
}
// Release consumer's semaphore
mSemConsumer.release();
return true;
}
public Object element()
{
// TODO Auto-generated method stub
return null;
}
public boolean offer(Object o)
{
// TODO Auto-generated method stub
return false;
}
public Object peek()
{
// TODO Auto-generated method stub
return null;
}
public Object poll()
{
// TODO Auto-generated method stub
return null;
}
public Object remove()
{
// TODO Auto-generated method stub
return null;
}
public boolean add(Object o)
{
// TODO Auto-generated method stub
return false;
}
public boolean addAll(Collection c)
{
// TODO Auto-generated method stub
return false;
}
public void clear()
{
// TODO Auto-generated method stub
}
public boolean contains(Object o)
{
// TODO Auto-generated method stub
return false;
}
public boolean containsAll(Collection c)
{
// TODO Auto-generated method stub
return false;
}
public boolean isEmpty()
{
// TODO Auto-generated method stub
return false;
}
public Iterator iterator()
{
// TODO Auto-generated method stub
return null;
}
public boolean remove(Object o)
{
// TODO Auto-generated method stub
return false;
}
public boolean removeAll(Collection c)
{
// TODO Auto-generated method stub
return false;
}
public boolean retainAll(Collection c)
{
// TODO Auto-generated method stub
return false;
}
public int size()
{
// TODO Auto-generated method stub
return 0;
}
public Object[] toArray()
{
// TODO Auto-generated method stub
return null;
}
public Object[] toArray(Object[] a)
{
// TODO Auto-generated method stub
return null;
}
}
Semaphore
最新推荐文章于 2022-02-25 20:00:37 发布