线程问题

cdzmy 2016-10-02 11:32:49
/*卖煤案例,下面的程序可以实现一个线程输入煤600块,另外一个线程分三次运出。问题如何修改:使得在运出的过程中,是多个线程参与运出:而不是单一的一个线程*/

package 国庆快乐;

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);
}
}
}
...全文
300 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
捏造的信仰 2016-10-04
  • 打赏
  • 举报
回复
楼主要学会贴代码
public class Demo {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("no args.");
        }
    }
}
像楼主的代码层级多,又没有排版,没法看。
cdzmy 2016-10-03
  • 打赏
  • 举报
回复
编辑的时候没有注意,sorry
上划线 2016-10-02
  • 打赏
  • 举报
回复
先把代码格式调整好吧

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧