用Java编写一个简单的存款
大家讲道理
大家讲道理 2017-04-18 10:53:05
0
2
453
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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
刘奇

多个线程访问同一个对象时,加synchronized(this)可以让一个时间内只有一个线程处理,但是你这里new了3个对象。

阿神

我感觉要怀疑的你的eclipse了,我完全复制的代码,重新运行了一遍,结果是这样的:
没有重复的数字,按照顺序依次存钱啊,结果也是正确的

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!