亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

用Java編寫一個(gè)簡單的存款
大家講道理
大家講道理 2017-04-18 10:53:05
0
2
543
package desposit.money;

public class DespositMoney {

    public static void main(String[] args) {
        Customer c1 = new Customer("第一個(gè)顧客",3);
        Customer c2 = new Customer("第二個(gè)顧客",10); 
        Customer c3 = new Customer("第三個(gè)顧客",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+"存款結(jié)束");
                    break;
                }
            }
        }
    }    
    
}

class Total {
    public static int sum = 0;
}

運(yùn)行結(jié)果不是從100,200,......,到1800,中間總有重復(fù)的數(shù)字,但最后的結(jié)果總和是1800

大家講道理
大家講道理

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

reply all(2)
劉奇

When multiple threads access the same object, adding synchronized(this) can allow only one thread to process it at a time, but you have 3 new objects here.

阿神

I feel like I have to doubt your eclipse. I copied the code completely and re-ran it. The result is this:
There are no repeated numbers. I deposit money in order and the result is also correct

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template