1. 程式人生 > >java多執行緒 kfc 生產者消費者問題

java多執行緒 kfc 生產者消費者問題

package threadpractice.practice2;

public class KFC{

volatile static int num = 0;

public KFC() {

}

public void producer() {
synchronized (this) {
while(num>=100) {
System.out.println("食材滿了");
try {
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
num++;
this.notifyAll();
System.out.println("生產了一個食物,當前數量"+String.valueOf(num));
}
}



public void consumer(String name) {
synchronized (this) {
while(num<1) {
try {
this.notifyAll();
System.out.println(name+"食物沒有了");
this.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
num--;
System.out.println(name+"買了一個");
}
}



public static void main(String[] args) {
KFC kfc = new KFC();

emp e = new emp(kfc);
emp e1 = new emp(kfc);
emp e2 = new emp(kfc);

cons c= new cons(kfc,"1");
cons c1= new cons(kfc,"2");
cons c2= new cons(kfc,"3");
Thread t2 = new Thread(e);
Thread t1 = new Thread(c);
Thread t3 = new Thread(c1);
Thread t4 = new Thread(c2);
Thread t5 = new Thread(e1);
Thread t6 = new Thread(e1);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}

}

class emp implements Runnable{


private KFC kfc;

public emp(KFC kfc) {
this.kfc = kfc;
}

@Override
public void run() {

this.kfc.producer();

}



}

class cons implements Runnable{


private KFC kfc;

private String name;

public cons(KFC kfc,String name) {
this.kfc = kfc;
this.name = name;
}

@Override
public void run() {
this.kfc.consumer(this.name);
}

}