public class ProducerConsumer {
/**
* @两个生产者一起生产,把product放入栈中,如果满了,等待消费者消费。
* @一个消费者消费,从栈中取,如果没有了,等待生产者生产
*/
public static void main(String[] args) {
Stack s = new Stack();
new Thread(new Producer(s)).start();
new Thread(new Producer(s)).start();
new Thread(new Consumer(s)).start();
}
}
class Digua{
private int id;
public Digua(int id){
this.id = id;
}
public int getId(){
return id;
}
}
class Stack{
private int count;
private Digua[] ds;
public Stack(){
ds = new Digua[6];
}
//生产
public synchronized void push(Digua d){
while(count==ds.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
System.out.println("生产者:"+d.getId());
ds[count++] = d;
}
//消费
public synchronized void pop(){
while(count==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
count--;
System.out.println("消费者:"+ds[count].getId());
}
}
//生产者
class Producer implements Runnable {
private static Stack s;
public Producer(Stack s){
this.s = s;
}
public void run(){
for(int i=1;i<=3;i++){
s.push(new Digua(i));
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//消费者
class Consumer implements Runnable{
private static Stack s;
public Consumer(Stack s){
this.s = s;
}
public void run(){
for(int i=1;i<=12;i++){
s.pop();
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
/**
* @两个生产者一起生产,把product放入栈中,如果满了,等待消费者消费。
* @一个消费者消费,从栈中取,如果没有了,等待生产者生产
*/
public static void main(String[] args) {
Stack s = new Stack();
new Thread(new Producer(s)).start();
new Thread(new Producer(s)).start();
new Thread(new Consumer(s)).start();
}
}
class Digua{
private int id;
public Digua(int id){
this.id = id;
}
public int getId(){
return id;
}
}
class Stack{
private int count;
private Digua[] ds;
public Stack(){
ds = new Digua[6];
}
//生产
public synchronized void push(Digua d){
while(count==ds.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
System.out.println("生产者:"+d.getId());
ds[count++] = d;
}
//消费
public synchronized void pop(){
while(count==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
count--;
System.out.println("消费者:"+ds[count].getId());
}
}
//生产者
class Producer implements Runnable {
private static Stack s;
public Producer(Stack s){
this.s = s;
}
public void run(){
for(int i=1;i<=3;i++){
s.push(new Digua(i));
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//消费者
class Consumer implements Runnable{
private static Stack s;
public Consumer(Stack s){
this.s = s;
}
public void run(){
for(int i=1;i<=12;i++){
s.pop();
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}