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

여러 스레드가 동일한 개체에 액세스할 때 동기화(this)를 추가하면 한 번에 하나의 스레드만 처리할 수 있지만 여기에는 3개의 새 개체가 있습니다.

阿神

일식을 의심해봐야 할 것 같습니다. 코드를 완전히 복사해서 다시 실행해 보니
순서대로 입금한 것도 없고 결과도 정확합니다. 🎜 >

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!