队列的设计
public class Buffer<T> {
private T[] data;
private int size;
private boolean empty;
private int reader;
private int writer;
public boolean isEmpty() {
return reader == writer;
}
public boolean isFull(){
return (writer + 1) % size == reader;
}
public int size(){
return (writer + size - reader) % size;
}
public Buffer(Class clazz, int size) {
this.data = (T[]) Array.newInstance(clazz, size + 1);
this.size = size + 1;
this.reader = 0;
this.writer = 0;
this.empty = true;
}
public boolean push(T ele){
if(isFull()){
return false;
}
data[writer] = ele;
writer = (++writer) % size;
return true;
}
public T pop(){
if(isEmpty()){
return null;
}
T val = data[reader];
reader = (++reader) % size;
return val;
}
public synchronized void produce(T ele){
while (isFull()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.push(ele);
System.out.println(Thread.currentThread().getName() + ":" + ele);
this.notify();
}
public synchronized void consume(){
while (isEmpty()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T data = this.pop();
System.out.println(Thread.currentThread().getName() + ":" + data);
this.notify();
}
}
生产者设计
public class Producer implements Runnable{
private final Buffer<Integer> buffer;
public Producer(Buffer<Integer> buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
Random rand = new Random();
while (true){
int random = rand.nextInt(100);
buffer.produce(random);
}
}catch (Exception e) {
System.err.println("hit Exception" + e);
}
}
}
消费者设计
public class Consumer implements Runnable{
private final Buffer<Integer> buffer;
public Consumer(Buffer<Integer> buffer) {
this.buffer = buffer;
}
@Override
public void run() {
try {
while (true){
Thread.sleep(3000);
buffer.consume();
}
}catch (Exception e) {
System.err.println("hit Exception" + e);
}
}
}
改动点:将对Buffer的消费和生产的同步操作放到Buffer内部。