package LessonTwo;
public class producerCustomer02 {
public static void main(String[] args) {
database d = new database();
Thread pr = new Thread(new producer(d));
Thread cu = new Thread(new customer(d));
pr.start();
cu.start();
}
}
class rice{
public static int id = 0;
rice(int dex){
id = dex;
}
}
class database{
private static int index = 0;
rice[] mRice = new rice[6];
public synchronized void push (rice rc){
while (index == mRice.length){
System.out.println("****** 仓库已经满满的了 *******");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
mRice[index++] = rc;
System.out.println(("生产了产品 "+rc.id+" 仓库总数为:"+index));
}
synchronized rice pop(){
while (index == 0){
System.out.println("******** 仓库空空如也 ********");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
--index;
rice rc = mRice[index];
System.out.println(("消费了产品 "+rc.id+" 仓库总数为:"+index));
return rc;
}
}
class producer implements Runnable{
database db = new database();
public producer(database dab){
db = dab;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++){
db.push(new rice(i));
try {
Thread.sleep((int) (Math.random()*500));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class customer implements Runnable{
database db = new database();
public customer(database dab){
db = dab;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++){
db.pop();
try {
Thread.sleep((int) (Math.random()*500));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
生产者生产大米存入仓库,消费者从仓库中消费大米。
生产者消费者使用多线程模拟,仓库中可以存放6袋大米。当仓库存满时,生产者线程 等待,同时释放线程锁。
消费者线程继续运行,同时唤醒线程,达到模拟生产者消费者的效果。