问题描述:
生产者:爸爸、妈妈
消费者:child1、child2、child3
临界资源:盘子里面放的苹果,最多放10个苹果
代码展示:
苹果类:
package com.niuke.proccon;
/**
* Created by panlu on 16-9-8.
*/
public class Apple {
private int appleID = 0;
public Apple(int appleID) {
this.appleID = appleID;
}
public int getAppleID() {
return appleID;
}
public void setAppleID(int appleID) {
this.appleID = appleID;
}
}
盘子类:
public class Dish {
private Apple[] apples = new Apple[10];
private int curnum = 0;
private Integer procedureumber = null;
private Integer consumenumber = null;
public synchronized void pushApple(Apple apple){
procedureumber = new Integer(curnum);
synchronized (procedureumber) {
if (curnum == apples.length) {
try {
System.out.println("盘子已满,等待消费...");
wait(); //wait是属于object的方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}
apples[curnum] = apple; //将苹果放入到盘子里面
curnum++;
}
}
public synchronized Apple popApple() {
consumenumber = new Integer(curnum);
synchronized (consumenumber) {
if (curnum == 0) {
notifyAll();
try {
System.out.printf("盘子为空,等待生产...");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Apple apple = apples[curnum];
apples[curnum] = null;
curnum--;
return apple;
}
}
}
消费者:
public class Consumer implements Runnable {
private String consumername;
private Dish dish = null;
public Consumer(String consumername,Dish dish) {
this.consumername = consumername;
this.dish = dish;
}
public String getConsumername() {
return consumername;
}
public void setConsumername(String consumername) {
this.consumername = consumername;
}
@Override
public void run() {
int i = 1;
while (true){
Apple apple = dish.popApple();
System.out.println(this.getConsumername()+"吃掉了第"+i+"个苹果");
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者:
public class Procdure implements Runnable{
private String procdureName;
private Dish dish = null;
public Procdure(String procdureName, Dish dish) {
this.procdureName = procdureName;
this.dish = dish;
}
public String getProcdureName() {
return procdureName;
}
public void setProcdureName(String procdureName) {
this.procdureName = procdureName;
}
@Override
public void run() {
int i = 1;
while (true){
Apple apple = new Apple(i);
dish.pushApple(apple);
System.out.println(this.getProcdureName() + "生产了第" + i + "个苹果");
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
主类:
public class ProcdureConsumer {
public static void main(String[] args) {
Dish dish = new Dish(); //创建一个盘子
Procdure mom = new Procdure("mom",dish); //生产者1
Procdure dad = new Procdure("dad",dish); //生产者2
Consumer child1 = new Consumer("child1",dish); //消费者1
Consumer child2 = new Consumer("child2",dish); //消费者2
Consumer child3 = new Consumer("child3",dish); //消费者3
new Thread(mom).start();
new Thread(dad).start();
Thread th1 = new Thread(child3);
th1.setPriority(6);
th1.start();
Thread th2 = new Thread(child1);
th2.setPriority(7);
th2.start();
Thread th3 = new Thread(child2);
th3.setPriority(10);
th3.start();
}
}