Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1216624
  • 博文数量: 788
  • 博客积分: 4000
  • 博客等级: 上校
  • 技术积分: 7005
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-19 15:52
文章存档

2017年(81)

2011年(1)

2009年(369)

2008年(337)

分类: 敏捷开发

2017-10-14 22:27:39

package desposit.money;

public class DespositMoney {

    public static void main(String[] args) {
        Customer c1 = new Customer("第一个顾客",3);
        Customer c2 = new Customer("第二个顾客",10); 
        Customer c3 = new Customer("第三个顾客",5); 

        c1.start();
        c2.start();
        c3.start();
    }

}

class Customer extends Thread{
    private int time;
    String s;
    public Customer(String s,int time){
        this.s = s;
        this.time = time;
    }
    public void run(){
        while(true)
        {
            synchronized(this){
                            
                if(time>0)    
                {
                    Total.sum+=100;
                    System.out.println(s+"存款100元,银行总共有存款"+Total.sum+"元");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time --;
                }
                    
                if(time ==0)
                {
                    System.out.println(s+"存款结束");
                    break;
                }
            }
        }
    }    
    
}

class Total {
    public static int sum = 0;
}

运行结果不是从100,200,......,到1800,中间总有重复的数字,但最后的结果总和是1800




这个答案描述的挺清楚的:
阅读(1407) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~