首页 > 编程语言 > 详细

java多线程 kfc 生产者消费者问题

时间:2018-12-10 21:38:17      阅读:256      评论:0      收藏:0      [点我收藏+]

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);
}

}

java多线程 kfc 生产者消费者问题

原文:https://www.cnblogs.com/xxfxxf/p/10099062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!