容器类:
package com.mjt.thread;
public class Collection {
private String goods[] = new String[10];
private int index = 0;
public synchronized void put(String cargo) {
if(index == 10) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
goods[index] = cargo;
index++;
notify();
}
public synchronized String get() {
if(index == 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
index --;
String ret = goods[index];
notify();
return ret;
}
}
生产者:
package com.mjt.thread;
public class Producer implements Runnable {
int i = 1;
private Collection collection;
Producer(Collection collection) {
this.collection = collection;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
collection.put("货物"+i);
System.out.println("生产了"+"货物"+i);
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
消费者:
package com.mjt.thread;
public class Consumer implements Runnable {
private Collection collection;
Consumer(Collection collection) {
this.collection = collection;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
System.out.println("客户消费了"+collection.get());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
工厂类(生产车间)
package com.mjt.thread;
public class Factory {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection c = new Collection();
new Thread(new Producer(c)).start();
new Thread(new Consumer(c)).start();
}
}