黑马程序员技术交流社区

标题: 线程问题 [打印本页]

作者: juanjuan    时间: 2016-10-6 01:52
标题: 线程问题
/*卖煤案例,下面的程序可以实现一个线程输入煤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);
}
}
}
作者: 李春林    时间: 2016-10-6 07:11
人工顶贴!!!!!!!

作者: 易东伟    时间: 2016-10-6 10:49
自己定义一个类变量,在定一个方法,三个线程运行就好了呀





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2