关于Runnables实现多线程的问题
三棵树aa 2016-07-17 06:15:44 //两个储户往同一个账户存钱
public class ThreadAccount{
public static void main(String[] args) {
Customer a = new Customer(5,1000);
Thread customer1 = new Thread(a) ;
Thread customer2 = new Thread(a);
customer1.setName("储户一");
customer2.setName("储户二");
customer1.start();
customer2.start();
}
}
class Account{
private double instance;
void deposit(int time,double money ){
int i =0;
while (true) {
synchronized (this) {
if (i < time) {
instance += money;
System.out.println(Thread.currentThread().getName() + "存钱"
+ money + "\t余额:" + instance);
i++;
}
}
}
}
}
class Customer implements Runnable {
private int time;
private double money;
Account account =new Account(); 直接创建账户对象,为什么是给相同的账户存钱
//time:存款次数 money:每次存款金额
public Customer(int time, double money) {
super();
this.time = time;
this.money = money;
}
public void run() {
// TODO Auto-generated method stub
System.out.println(account);
account.deposit(time,money);
}
}