Producer.java
package thread;
public class Producer implements Runnable{
private SyncStack stack;
private int num;
private static int counter=1;
    
public Producer(SyncStack stack){
this.stack=stack;
num=counter;
}
    
public void run(){
char c;
for(int i=0;i<200;i++){
c=(char)(Math.random()*100+'A');
stack.push(c);
num++;
System.out.println("生产者:"+num+" "+c);

try{
Thread.sleep(2000);
}catch(Exception e){

}
}
}}Customer.java
package thread;
public class Customer implements Runnable{

private SyncStack stack;
private int num;

public Customer(SyncStack stack){
this.stack=stack;
num=1;
}

public void run(){
char c;
for(int i=0;i<200;i++){
c=stack.pop();
num--;
System.out.println("消费者:"+num+":"+c);

try{
Thread.sleep(2000);
}catch(InterruptedException e){

}
}
}}共享类
package thread;import java.util.ArrayList;
import java.util.List;public class SyncStack {

private List buffer=new ArrayList();

public synchronized char pop(){
char c;
while(buffer.size()==0){
try{
this.wait();
}catch(InterruptedException e){

}
this.notify();
}
c=((Character)buffer.get(buffer.size()-1)).charValue();
buffer.remove(c);
return c;
}

public synchronized void push(char c){

while(buffer.size()>10){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
this.notify();
}

Character charObj=new Character(c);
buffer.add(charObj);
}}
测试类
package thread;public class Test {

public static void main(String args[]){

SyncStack stack=new SyncStack();

Producer producer1=new Producer(stack);
Thread thread1=new Thread(producer1);
thread1.start();

Producer producer2=new Producer(stack);
Thread thread2=new Thread(producer2);
thread2.start();

Customer consumer1=new Customer(stack);
Thread thread3=new Thread(consumer1);
thread3.start();

Customer consumer2=new Customer(stack);
Thread thread4=new Thread(consumer2);
thread4.start();
}}
java多线程exception