您的位置:首页 > 职场人生

java多线程模拟生产者消费者问题,公司面试常常问的题。。。

2015-03-31 11:16 633 查看
package com.cn.test3;

//java多线程模拟生产者消费者问题
//ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品
//Storage仓库
//批注:我把输出结果写在程序以下了,你能够看一下,事实上非常easy的,你想象一下产品从生产,到取出的一个生产线,我们定义两个线程,生产者线程,和消费者线程,一个是生产者不停的生产产品并放入数量有限的指定槽内,而消费者从指定槽依次取出产品,现实中的流水车间也相似于此。
public class test3 {

public static void main(String[] args) {
Storage s = new Storage();
Producer p = new Producer(s);
Consumer c = new Consumer(s);
Thread tp = new Thread(p);
Thread tc = new Thread(c);
tp.start();
tc.start();
}
}
class Consumer implements Runnable {//消费者
Storage s = null;
public Consumer(Storage s){
this.s = s;
}
public void run() {
for(int i=0; i<10; i++){//这里的10指的是10个产品,依据生产者生产的产品数量一致,生产者生产10个产品,消费者肯定仅仅能取出10个产品。
Product p = s.pop();//取出产品
try {
Thread.sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}

class Producer implements Runnable {//生产者
Storage s = null;

public Producer(Storage s){
this.s = s;
}

public void run() {
//总共生产10个产品
for(int i=0; i<10; i++){//这里的10能够任意改动,看你想让生产者生产多少产品了,我们如今假定生产10个产品就停止,能够參考程序的 输出。
Product p = new Product(i);
s.push(p);	//放入产品
//			System.out.println("生产者放入:" + p);
try {
Thread.sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}

class Product {
int id;

public Product(int id){
this.id = id;
}

public String toString(){//重写toString方法
return "产品:"+this.id;
}
}

class Storage {
int index = 0;
//仓库存储量最大也仅仅有三个位置。//这个就是指生产者把产品生产出来,放入到指定“槽”内,我们如今假定,槽仅仅有3个槽,当然你能够设定多个,当生产者
//把产品都占满了3个槽的情况时,那仅仅能等消费者取出一个槽内的产品才干继续生产产品以放到槽内。。能够理解吧。。
Product[] products = new Product[3];

synchronized public void push(Product p){//放入,放入和取出代码是要加锁的,这个能够理解吧。。这段代码要么不运行,要么运行完。。。
while(index==this.products.length){
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.products[index] = p;
System.out.println("生产者放入"+index+"位置:" + p);
index++;
this.notifyAll();
}

public synchronized Product pop(){//取出
while(this.index==0){
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
index--;
this.notifyAll();
System.out.println("消费者从"+ index+ "位置取出:" + this.products[index]);
return this.products[index];
}
}
输出结果:
生产者放入0位置:产品:0消费者从0位置取出:产品:0生产者放入0位置:产品:1消费者从0位置取出:产品:1生产者放入0位置:产品:2生产者放入1位置:产品:3消费者从1位置取出:产品:3生产者放入1位置:产品:4消费者从1位置取出:产品:4消费者从0位置取出:产品:2生产者放入0位置:产品:5消费者从0位置取出:产品:5生产者放入0位置:产品:6消费者从0位置取出:产品:6生产者放入0位置:产品:7生产者放入1位置:产品:8消费者从1位置取出:产品:8生产者放入1位置:产品:9消费者从1位置取出:产品:9消费者从0位置取出:产品:7

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: