package test_1;
public class BigSmallMonk
{
public static void main(String[] args)
{
WaterIntake Omonk=new WaterIntake();
PouringWater Ymonk=new PouringWater();
Thread Ymonk1=new Thread(Ymonk);
Ymonk1.setName("Ymonk1");
Thread Omonk1=new Thread(Omonk);
Omonk1.setName("Omonk1");
Ymonk1.start();
Omonk1.start();
}
}
class WaterTank//水缸
{
static int num=30;//水缸所能承受水的桶数
static int currentNum=0;//水缸里现有的水的桶数
static boolean flag = true;//缸口是否有人使用
public void reduce()//取水
{
synchronized (this)
{
while (!flag)
{
try
{
System.out.println("缸口有人使用");
this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//这里不需要设置false,因为你这样一设置,另外一个线程总是执行那个while里并且在wait了。
//flag=false;
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
currentNum--;
flag=true;
this.notify();
System.out.println(Thread.currentThread().getName()+"取出了水");
}
}
public void push()//倒水
{
synchronized (this)
{
while (!flag)
{
try
{
System.out.println("缸口有人使用");
this.wait();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//这里不需要设置false,因为你这样一设置,另外一个线程总是执行那个while里并且在wait了。
//flag=false;
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
currentNum++;
flag=true;
this.notify();
System.out.println(Thread.currentThread().getName()+"倒入了一桶水");
}
}
}
class WaterIntake implements Runnable//取水线程
{
WaterTank water=new WaterTank();
public void run()
{
while (true)
{
water.reduce();
}
}
}
class PouringWater implements Runnable//倒水线程
{
WaterTank water=new WaterTank();
public void run()
{
while(true)
{
water.push();
}
}
}