/*卖煤案例,下面的程序可以实现一个线程输入煤600块,另外一个线程分三次运出。问题如何修改:使得在运出的过程中,是多个线程参与运出:而不是单一的一个线程*/
求解,谢谢@_@
public class CoalDemo {
public static void main(String[] args)
{
Coal c=new Coal();
InputCoal in=new InputCoal(c);
OutCoal o=new OutCoal(c);
for(int i=0;i<2;i++)
{
new Thread(in).start();
//try{Thread.sleep(100);}catch(Exception e){}
}
for(int i=0;i<3;i++)
{
new Thread(o).start();
//try{Thread.sleep(100);}catch(Exception e){}
}
}
}
class Coal
{
int Coal;
boolean flag=false;
public synchronized void setCoal(int Coal)
{
while(flag)
{
try{this.wait();}catch(Exception e){};
}
this.Coal+=Coal;
System.out.println(Thread.currentThread().getName()
+"运进了..."+Coal+"煤");
System.out.println("煤库中剩余煤的数量..."+this.Coal);
flag=true;
this.notifyAll();
}
public synchronized void getCoal(int Coal)
{
if(this.Coal<=0)
{
while(!flag)
try{this.wait();}catch(Exception e){};
}
this.Coal-=Coal;
System.out.println(Thread.currentThread().getName()
+"运出了..."+Coal+"煤");
System.out.println("煤库中剩余煤的数量..."+this.Coal);
flag=false;
this.notifyAll();//如果是notifyall,必须用while进行循环判断,notify用if判断
}
}
class InputCoal implements Runnable
{
Coal c;
InputCoal(Coal c)
{
this.c=c;
}
public void run()
{
while(true)
{
c.setCoal(600);
}
}
}
class OutCoal implements Runnable
{
Coal c;
OutCoal(Coal c)
{
this.c=c;
}
public void run()
{
while(true)
{
c.getCoal(200);
}
}
} |
|