java生产消费者模式

来源:互联网 发布:jquery weui.min.js 编辑:程序博客网 时间:2024/04/30 13:42
package productiveConsumption2;


/*
 * 面包类
 */
public class Bread {
private int id;
private String name;


public Bread(int id, String name) {
super();
this.id = id;
this.name = name;
}


public Bread() {
super();
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


@Override
public String toString() {
return "Bread [id=" + id + ", name=" + name + "]";
}


}


package productiveConsumption2;

//超市类
public class SuperMarket {
// 存面包的数量
Bread[] breads = new Bread[10];
// 记录下标
int index = -1;


// 进面包
public synchronized void getBread(Bread bread) {
if (index >= breads.length - 1) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
index++;
breads[index] = bread;
System.out.println("进面包:" + bread);
this.notify();
}


// 卖面包
public synchronized void saleBread() {
if (index < 0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("卖面包:" + breads[index]);
index--;
this.notify();
}
}

package productiveConsumption2;


/*
 * 消费者
 */
public class Coustomer implements Runnable {
private SuperMarket market;


public Coustomer(SuperMarket market) {
super();
this.market = market;
}


@Override
public void run() {
for (int i = 1; i <= 20; i++) {
market.saleBread();
}


}


}

package productiveConsumption2;
/*
 * 工厂类
 */
public class Factory implements Runnable{
private SuperMarket market;

public Factory(SuperMarket market) {
super();
this.market = market;
}


@Override
public void run() {
for (int i = 1; i <= 20; i++) {
market.getBread(new Bread(i, "好吃面包" + i));
}

}


}

package productiveConsumption2;
/*
 * 测试类
 */
public class Test {


public static void main(String[] args) {
SuperMarket m = new SuperMarket();
Coustomer c = new Coustomer(m);
Factory f = new Factory(m);
Thread t1 = new Thread(c);
Thread t2 = new Thread(f);
t1.start();
t2.start();


}


}

0 0
原创粉丝点击