即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

java生产消费者模式

编程语言 weishimeng17 9℃ 0评论

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();








}








}

转载请注明:CodingBlog » java生产消费者模式

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情