import java.util.Random;
/*
* @topic:用互斥实现生产者消费者问题
*/
public class Custom{
public static void main(String[] args) {
FruitBasket fb = new FruitBasket();
new Thread(new Farmer("农夫1",fb)).start();
new Thread(new Farmer("农夫2",fb)).start();
new Thread(new Farmer("农夫3",fb)).start();
new Thread(new Child("小孩1",fb)).start();
new Thread(new Child("小孩2",fb)).start();
new Thread(new Child("小孩3",fb)).start();
}
}
class Fruit{
private int id;
private static int number = 0;
private String variety;
private String[] varietys = "苹果,桃子,梨子,香蕉,西瓜,荔枝,葡萄".split(",");
public Fruit(){
this.variety = varietys[new Random().nextInt(7)];
this.id = ++number;
}
public int getId(){
return this.id;
}
public String getVariety(){
return this.variety;
}
}
class FruitBasket{
private Fruit[] fruits = new Fruit[10];//容量为10的水果数组
private int index = 0;//下一个将要放入水果的位置
public boolean isEmpty(){//判断水果篮是否为空
return index == 0 ?true:false;
}
public boolean isFull(){//是否为满
return index == fruits.length?true:false;
}
public synchronized void push(String name , Fruit fruit){//对push方法实行同步
while(isFull()){
try{
this.wait();//若为满,则不能push,只能等待。
}catch(InterruptedException e){
e.printStackTrace();
}
}
fruits[index++] = fruit;
System.out.println(name + "向水果框中放入编号为" + fruit.getId() + "的"+fruit.getVariety());
display();
this.notify(); //通知另一线程
}
public synchronized Fruit pop(String name){
while(isEmpty()){
try{
this.wait();
}catch(Exception e){
e.printStackTrace();
}
}
Fruit fruit = fruits[--index];
System.out.println(name + "从水果框中拿出编号为"+fruit.getId() +"的" + fruit.getVariety());
display();
this.notify();
return fruit;
}
public void display(){
for(int i = 0 ; i < index ; i++){
System.out.printf(fruits[i].getId()+fruits[i].getVariety() + " |");
}
for (int i = index; i < fruits.length; i++) {
System.out.printf( "[" + (i + 1) + "]|");
}
System.out.println("\n");
}
}
class Farmer implements Runnable{
private String name ;
private FruitBasket fruitBasket;
public void run(){//不断往篮子中放
while(true){
fruitBasket.push(name,new Fruit());
try{
Thread.sleep(new Random().nextInt(2000));
}catch(Exception e){
e.printStackTrace();
}
}
}
Farmer(String name, FruitBasket fruitBasket) {
this.name = name;
this.fruitBasket = fruitBasket;
}
}
class Child implements Runnable{
private String name;
private FruitBasket fruitBasket;
public void run(){//不断往篮子中取
while(true){
fruitBasket.pop(this.name);
try{
Thread.sleep(new Random().nextInt(5000));
}catch(Exception e){
e.printStackTrace();
}
}
}
Child(String name, FruitBasket fruitBasket) {
this.name = name;
this.fruitBasket = fruitBasket;
}
}
java多线程应用——生产者消费者
最新推荐文章于 2022-04-24 14:35:23 发布