先创建一个仓库类
public class changku {
LinkedList<Object> list =new LinkedList<Object>();
private static final int MAX=100;
public synchronized void shengcan(String pr) {
while(list.size()>MAX) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"++生产了"+pr);
list.offer(pr);
this.notifyAll();
}
public synchronized void xiaofei() {
while(list.size()<=0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Object pr=list.poll();
System.out.println(Thread.currentThread().getName()+"消费了"+pr);
this.notifyAll();
}
}
在创建一个生产者类,继承Thread
public class scz extends Thread{
private changku ck;
public scz(changku ck) {
super();
this.ck = ck;
}
@Override
public void run() {
for(int i=1;i<=30;i++) {
String st="编号:"+new Random().nextInt(100);
ck.shengcan(st);
}
}
}
在创建一个消费者类,同样继承Thread
public class xfz extends Thread{
private changku ck;
public xfz(changku ck) {
super();
this.ck = ck;
}
@Override
public void run() {
for(int i=1;i<=30;i++) {
ck.xiaofei();
}
}
}
最后建立测试类,来测试
public class Text {
public static void main(String[] args) {
changku ckk =new changku();
//新建三个线程来模拟三个生产者
scz p1=new scz(ckk);
p1.setName("生产者1");
p1.start();
scz p2=new scz(ckk);
p2.setName("生产者2");
p2.start();
scz p3=new scz(ckk);
p3.setName("生产者2");
p3.start();
//新建三个线程来模拟三个消费者
xfz c1=new xfz(ckk);
c1.setName("消费者1");
c1.start();
xfz c2=new xfz(ckk);
c2.setName("消费者2");
c2.start();
xfz c3=new xfz(ckk);
c3.setName("消费者3");
c3.start();
}
}
英语不太好,所以类名都用拼音来代替