import java.util.LinkedList;
/**
* 公共资源
*
* @author
*
*/
class Resource4 {
private static LinkedList<Integer> shareResource = new LinkedList<Integer>();
private int N;// 缓冲区大小
private static volatile int number = 0;
public Resource4(int N) {
this.N = N;
}
public synchronized void produce() {
// TODO Auto-generated method stub
if (shareResource.size() >= N) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
++number;
shareResource.add(number);
System.out.println(Thread.currentThread().getName() + "生产了" + number);
notifyAll();
}
}
public synchronized void consumer() {
// TODO Auto-generated method stub
if (shareResource.size() <= 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
--number;
System.out.println(Thread.currentThread().getName() + "消费了" + shareResource.pollLast());
notifyAll();
}
}
}
/**
* 生产者,可以不断的生成产品
*
* @author
*
*/
class Producer4 implements Runnable {
private final Resource4 resource;
public Producer4(Resource4 resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
resource.produce();
}
}
}
/**
* 消费者, 只要缓存队列不为空,可以不断的消费
*
* @author
*
*/
class Consumer4 implements Runnable {
private final Resource4 resource;
public Consumer4(Resource4 resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
resource.consumer();
}
}
}
public class ProducerAndConsumer4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int N = 100;
Resource4 resource = new Resource4(N);
// 多个生成线程和消费者线程可以同时工作
for (int i = 0; i < 2; i++) {
new Thread(new Producer4(resource)).start();
new Thread(new Consumer4(resource)).start();
}
}
}