假设某银行可接受顾客的汇款,每进行一次汇款,便可计算出汇款的总额。现有两名顾客,
每人不论顺序分三次、每次10000以内不定金额。模拟顾客的汇款操作。
public class BankTransfer {
public static void main(String[] args) {
//创建两个Customer的对象
Customer c1 = new Customer();
Customer c2 = new Customer();
//利用start()方法调用类Customer的run方法
c1.start();
c2.start();
}
}
class Bank{
//balance用于记录银行总余额
private static int balance = 0;
//用synchronized关键字设定该方法为线程同步的
public synchronized static void take(int money) {
int temp = balance;
temp += money;
//利用sleep()方法令当前正在执行的线程进入休眠状态,且参数类型必须为int
try {Thread.sleep((int)(1000*Math.random()));}
catch(InterruptedException e) {}
balance = temp;
System.out.println("银行总余额为:" + balance);
}
}
//模拟用户存款的线程类
class Customer extends Thread{
public void run() {
//设定一个对象共存款三次
for (int i = 0;i < 3;i++) {
//每次随机存入不定金额
Bank.take((int)(10000*Math.random()));
}
}
}