生产者生产产品后将产品放在一个仓库里,消费者购买省商品相当于从仓库里拿出商品。这其中涉及到的有生产者、消费者与仓库以及产品四个对象,因此需要创建四个类来表示。最后还需要一个测试类。对于生成与消费这两个动作可是是同时执行的(只要有商品的话),因此需要使用到多线程的知识。
product类
public class Product{
private int id;
public Product41(
int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(
int id) {
this.id = id;
}
}
Storage类
public class Storage{
Product[] ps =
new Product[
10];
int index;
public synchronized void push(Prodeuct p){
while(index == ps.length){
try {
this.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
ps[index] = p;
index++;
}
public synchronized Product
pop(){
while (index ==
0) {
try {
this.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return ps[index];
}
}
Producer类
public class Producer extends Thread{
Storage storage;
public Producer(Storage storage){
this.storage = storage;
}
@override
public void run(){
System.out.println(
"生产者"+getName()+
"生产了一件商品");
Product p =
new Product(i);
storage.push(p);
try{
sleep(
300);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
Customer类
public class Customer extends Thread{
Storage storage;
public Customer(Storage storage){
this.storage = storage;
}
@override
public void run(){
for(
int i =
0; i <
20; i++){
Product p = storage.pop();
System.out.println(
"消费者"+getName()+
"消费了一件产品");
try {
sleep(
300);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
TestMain类
public class Test{
public static void main(String[] args){
Storage s =
new Storage();
Customer c1 =
new Customer(s);
c1.setName(
"c1");
Customer c2 =
new Customer(s);
c2.setName(
"c2");
Producer p1 =
new Producer(s);
p1.setName(
"p1");
Producer p2 =
new Producer(s);
p2.setName(
"p2");
p1.start();
p2.start();
c1.start();
c2.start();
}
}