线程同步的经典例子

银行存钱与取钱的例子能够很好的说明线程同步的概念

一:首先定义帐号类,其中有一个余额的字段:

 

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;
	}
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值