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

时间:2023-03-09 03:05:35
java多线程模拟生产者消费者问题,公司面试常常问的题。。。
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