银行存钱与取钱的例子能够很好的说明线程同步的概念
一:首先定义帐号类,其中有一个余额的字段:
public class BankAccount {
private int balance;//余额
public BankAccount( int balance) {
this.balance = balance;
}
/**
*返回余额
*/
public int getBalance() {
return balance;
}
/**
* 存款
*/
public void deposit(int amount) {
balance += amount;
}
/**
* 取款
*/
public void withdraw(int amount) {
balance -= amount;
}
}
二,新建存钱的线程,模拟存钱10000次
public class Depositor implements Runnable {
BankAccount account;
int amount;
public Depositor(BankAccount account, int amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
account.deposit(amount);
}
}
}
三:新建取钱的线程,模拟取钱10000次
public class Withdrawer implements Runnable {
BankAccount account;
int amount;
public Withdrawer(BankAccount account, int amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
account.withdraw(amount);
}
}
}
四,测试类
public class BankAccountTest {
public static void main(String[] args) throws InterruptedException{
BankAccount account = new BankAccount(1000);
Thread t1 = new Thread(new Depositor(account, 100), "depositor");
Thread t2=new Thread(new Withdrawer(account, 100),"withdrawer");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("余额:"+account.getBalance());
}
}
运行完成后,结果应该还是初始的1000才对。不幸的是,这样的运行结果是不正确的,而且每次结果还不一样。
五,如果将帐号类的取钱与存钱方法稍加改进,加上同步关键字,则结果就是对的:
public class BankAccount {
private int balance;
public BankAccount( int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
/**
* 存款
*/
public synchronized void deposit(int amount) {
balance += amount;
}
/**
* 取款
*/
public synchronized void withdraw(int amount) {
balance -= amount;
}
}