日期:2014-05-20 浏览次数:20870 次
class Food{
static boolean flag = true; // 设 true 需要生产
public synchronized void proFood(){
if(!flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("pppppppppp");
flag = false;
super.notify();
}
public synchronized void conFood(){
if(flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(1);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ccccccccc");
flag = true;
super.notify();
}
}
class Producer implements Runnable{
Food f = new Food();
public static int howMany;
Producer(int howMany){
this.howMany = howMany;
}
public void run(){
for(int i = 0; i < howMany; i++){
f.proFood();
}
}
}
class Consumer implements Runnable{
Food f = new Food();
public void run(){
for(int i = 0; i < Producer.howMany; i++){
f.conFood();
}
}
}
public class Test {
public static void main(String args[]) throws Exception{
Producer p = new Producer(10);
Consumer c = new Consumer();
new Thread(p).start();
new Thread(c).start();
}
}