基于ReentrantLock和Condition来实现的一个消息队列
provider生产者:
public class ProviderThread implements Runnable {
private ReentrantLockQueue<String> queue;
public ProviderThread(ReentrantLockQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
System.out.println("开始执行生产队列.....");
while (true){
String uuid = UUID.randomUUID().toString();
System.out.println("生产一个UUID:"+uuid);
try {
queue.pull(uuid);
System.out.println("已放入队列");
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
constume消息者
public class ConsumeThread implements Runnable {
private ReentrantLockQueue<String> queue;
public ConsumeThread(ReentrantLockQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
System.out.println("休眠5秒");
try {
Thread.sleep(5000);
System.out.println("开始进行消费UUID.....");
while (true){
String uuid = queue.task();
System.out.println("从队列中取出UUID:"+uuid);
System.out.println("开始休眠2秒");
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
ReentrantLockQueue实现
public class ReentrantLockQueue<T> {
private ArrayList<T> items=new ArrayList();
private int size =Integer.MAX_VALUE;
private ReentrantLock lock = new ReentrantLock(true);
private Condition empty = this.lock.newCondition();
private Condition full = this.lock.newCondition();
public ReentrantLockQueue() {
this(15);
}
public ReentrantLockQueue(int size){
this.size = size;
items= new ArrayList<>(size);
System.out.println(size);
System.out.println(items.size());
}
public T pull(T obj) throws InterruptedException {
lock.lock();
if(items.size()==this.size){
try {
System.out.println("队列已满,等待中.....");
full.await();
System.out.println("等待结束开始执行后续....");
} catch (InterruptedException e) {
e.printStackTrace();
full.signal();
throw e;
}
}
items.add(obj);
empty.signal();
lock.unlock();
return obj;
}
public T task() throws InterruptedException {
lock.lock();
if(items.isEmpty()){
try {
System.out.println("队列无数据,等待中.....");
empty.await();
} catch (InterruptedException e) {
e.printStackTrace();
empty.signal();
throw e;
}
}
System.out.println(items.size());
T obj = items.remove(0);
System.out.println(items.size());
full.signal();
return obj;
}
}
运行类
public class Main {
@Test
public void test3() throws InterruptedException {
ReentrantLockQueue<String> queue = new ReentrantLockQueue<>();
Thread thread = new Thread(new ProviderThread(queue));
Thread thread1 =new Thread(new ConsumeThread(queue));
System.out.println("开系统开始运行");
thread.start();
thread1.start();
LockSupport.park();
}
}