A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© juanjuan 中级黑马   /  2016-10-6 01:52  /  718 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*卖煤案例,下面的程序可以实现一个线程输入煤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);
}
}
}

2 个回复

正序浏览
自己定义一个类变量,在定一个方法,三个线程运行就好了呀
来自宇宙超级黑马专属苹果客户端来自宇宙超级黑马专属苹果客户端
回复 使用道具 举报
人工顶贴!!!!!!!
来自宇宙超级黑马专属苹果客户端来自宇宙超级黑马专属苹果客户端
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马