浅谈生产消费模式

[size=large][color=red]关于生产消费模式[/color][/size]
[size=x-small]关于生产消费模式,其实就是两个线程之间共用一个对象,并对该对象进行编辑,从而达到线程之间的通信![/size]

既然是生产消费模式,当然至少需要一个生产者,一个消费者,同时需要一个二者之间处理的对象啦!我们称呼这个对象为一个仓库,其中仓库需要两个方法,一个给生产者调用,一个给消费者,相当于生产者与消费者告诉仓库要干嘛了,然后仓库才去调用自身相应的方法;因此仓库的代码为:
package test.producer_consumer;

public class Pool {

public static int nums;
public static int max=5;

public synchronized void put() {
if (nums<max) {
nums++;
System.out.println(Thread.currentThread().toString()+"添加了--"+nums);
this.notifyAll();
}else {
System.out.println("已经装满了!");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void get() {
if (nums>0) {
System.out.println(Thread.currentThread().toString()+"取出了--"+nums);
nums--;
this.notifyAll();
}else {
System.out.println("已经不能再取了!");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

接着就是生产者与消费者:他们都需要知道清楚他们去处理的仓库是哪个,因此我们需要在new生产消费者的时候需要传一个仓库的对象;
下面是生产消费的代码;
package test.producer_consumer;
public class Producer extends Thread{
public Pool pool;
Producer(){}
Producer(Pool p){this.pool=p;}
@Override
public void run() {
while (true) {
pool.put();
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package test.producer_consumer;
public class Consumer extends Thread{
public Pool pool;
Consumer(){}
Consumer(Pool p){this.pool=p;}
@Override
public void run() {
while (true) {
pool.get();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

运行代码:
package test.producer_consumer;
//生产消费者模式--关于多线程
public class Producer_Consumer {
public static void main(String[] args) {
Pool pool=new Pool();//仓库对象
Producer producer=new Producer(pool);//指定哪个仓库
Consumer consumer=new Consumer(pool);//指定哪个仓库
producer.start();
consumer.start();
}
}

这是上周六面试的一道算法题。。祝大家天天好心情!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值