码迷,mamicode.com
首页 > 编程语言 > 详细

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

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

标签:art   wait   没有   void   exception   over   override   thread   try   

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 生产者消费者问题

标签:art   wait   没有   void   exception   over   override   thread   try   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!