package com.xujy.thread;
/**
* 有两个储户,每次向同一个账户存钱,一次存1000,各存了三次,打印出账户的余额,采用多线程的方式,保证线程是安全的
* @author Administrator
*
*/
public class AccountMoney {
public static void main(String[] args) {
Account account=new Account();
Custmer ct1=new Custmer(account);
Custmer ct2=new Custmer(account);
ct1.setName("线程1");
ct2.setName("线程2");
ct1.start();
ct2.start();
}
}
class Account{
double balance;
public synchronized void deposit(double amt){//synchronized的对象是account并且只有一个,不会发生线程安全问题.
balance+=amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":账户余额"+balance);
}
}
class Custmer extends Thread{
Account account;
public Custmer(Account account){
this.account=account;
}
@Override
public void run() {
for(int i=0;i<10;i++){
account.deposit(1000);
}
}
}