生产者消费者问题

/**

* 经典生产者消费者的问题

*

* 生产者消费者是两个线程 在run方法里面告诉他们放到哪一个容器里面就可以了 注意容器的拿和放的方法需要加上关键字synchronized

*

*/


public class ProducterConsumer {

public static void main(String[] args) {

Container cr = new Container();

Producter p = new Producter(cr);

Consumer c = new Consumer(cr);

//如果需要生产快一点可以改sleep的时间短一点

new Thread(p).start();

new Thread(c).start();

//如果是有很多生产者 则在Container的nachulai和fang方法里面需要改成notifyAll

}

}


//产品

class Product{

int id;

Product(int id){

this.id = id;

}

public String toString(){

return "Producr :"+ id;

}

}


//容器

class Container{

int index = 0;

//定义一个数组放产品

Product[] ptArray = new Product[6];


public synchronized void fang(Product p){

//放入的动作

while(index == ptArray.length){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.notify();

ptArray[index] = p ;

index ++ ;



}


public synchronized Product nachulai(){

while(index == 0){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.notify();

index --;

return ptArray[index];

}


}


//生产者 做成线程更符合 把生产的东西方法放入run方法

class Producter implements Runnable{

Container cr = null;

Producter(Container cr){

this.cr = cr;

}

public void run(){

for (int i = 0; i Product p = new Product(i);

cr.fang(p);

try {

Thread.sleep(2);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("生产了--"+ p);



}

}

}


//消费者 把生产的东西方法放入run方法

class Consumer implements Runnable{

Container cr = null;

Consumer(Container cr){

this.cr = cr;

}


public void run(){

for (int i = 0; i Product p = cr.nachulai();

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("消费了--"+ p);



}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值