写了一段生产者与消费者代码,有待改进
package test;
import java.util.Random;
//商品缓冲池
class Buffer {
private int[] NumberPool = null;
private int size; //缓冲池大小
private volatile int head = 0;
private volatile int tail = 0;
public Buffer(int count) {
size = count + 1;
NumberPool = count <= 0 ? new int[11] : new int[count + 1];
for(int i=0;i<size;i++){
NumberPool[i]=-1;
}
}
public boolean isEmpty() {
return head == tail ? true : false;
}
public boolean isFull() {
return (tail + 1) % size == head ? true : false;
}
public void push(int product) {
NumberPool[tail] = product;
tail = (tail + 1) % size;
}
public int pull() {
int number = NumberPool[head];
head = (head + 1) % size;
return number;
}
public int size() {
return size == 0 ? 0 : size - 1;
}
}
/**
* 生产者与消费者
* 可以有多个生产者与多个消费者
* 只能有一个生产者对buffer进行操作
* 只能有一个消费者对buffer进行操作
* 一个生产者和一个消费者可以同时对buffer进行操作
*/
class ProduceAndConsum {
private Buffer buffer;
private Object plock = new Object(); // produce lock
private Object clock = new Object(); // consume lock
private Object nlock = new Object(); // notify lock
public ProduceAndConsum(int bufferSize) {
buffer = new Buffer(bufferSize);
}
public void Produce() throws InterruptedException{
int product=new Random().nextInt(Integer.MAX_VALUE);
synchronized (plock) {
if (buffer.isFull()) {
synchronized (nlock) {
System.out.println("buffer is full");
nlock.wait();//等待consum
}
} else {
buffer.push(product);
System.out.println(Thread.currentThread().getName()+"->push: " + product);
synchronized (nlock) {
nlock.notifyAll(); //唤醒consum
}
}
}
}
public void Consum() throws InterruptedException {
synchronized (clock) {
if (buffer.isEmpty()) {
synchronized (nlock) {
System.out.println("buffer is empty");
nlock.wait();//等待product
}
} else {
System.out.println(Thread.currentThread().getName()+"->pull: " + buffer.pull());
synchronized (nlock) {
nlock.notifyAll(); //唤醒product
}
}
}
}
}
public class test {
public static void main(String[] args) {
ProduceAndConsum pc = new ProduceAndConsum(100);
Runnable produce=new Runnable() {
@Override
public void run() {
while (true) {
try {
pc.Produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Runnable consum=new Runnable() {
@Override
public void run() {
while (true) {
try {
pc.Consum();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread p1=new Thread(produce,"p1");
Thread p2=new Thread(produce,"p2");
Thread p3=new Thread(produce,"p3");
Thread c1=new Thread(consum,"c1");
Thread c2=new Thread(consum,"c2");
Thread c3=new Thread(consum,"c3");
Thread c4=new Thread(consum,"c4");
Thread c5=new Thread(consum,"c5");
Thread c6=new Thread(consum,"c6");
Thread c7=new Thread(consum,"c7");
Thread c8=new Thread(consum,"c8");
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
c3.start();
c4.start();
c5.start();
c6.start();
c7.start();
c8.start();
}
}