标签:printf 方法 oid turn span 线程 his 开发 ace
在多线程开发中,总会遇到多个在不同线程中的方法操作同一个数据,这样在不同线程中操作这个数据不同的顺序
或者时机会导致各种不同的现象发生,以至于不能实现你预期的效果,不能实现一致性,这时候就能够使用
synchronizedkeyword对一个方法来说,这个synchronized能保证全部调用这种方法的线程仅仅有一个正在操作这种方法。
不会出现同一时候多个线程进入这种方法的情况,以下我们来一个样例说明这个情况。
首先是一个Account类,这个类模拟账户,提供添加工资和降低工资的方法,当然。这种方法是被synchronized控制
package com.bird.concursey.charpet2; public class Account { private double balance; public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public synchronized void addAmount(double amount) { double temp = balance; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } temp += amount; balance = temp; } public synchronized void subtractAmount(double amount) { double temp = balance; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } temp -= amount; balance = temp; } }
然后是两个模拟类,来模拟使用这个类来添加或者降低账户的剩余金额
package com.bird.concursey.charpet2; public class Bank implements Runnable { private Account account; public Bank(Account account) { this.account = account; } @Override public void run() { for(int i = 0; i < 100; i++) { account.subtractAmount(1000); } } }
package com.bird.concursey.charpet2; public class Company implements Runnable { private Account account; public Company(Account account) { this.account = account; } @Override public void run() { for(int i = 0; i < 100; i++) { account.addAmount(1000); } } public static void main(String[] args) { Account account = new Account(); account.setBalance(1000); Company company = new Company(account); Thread companyThread = new Thread(company); Bank bank = new Bank(account); Thread bankThread = new Thread(bank); System.out.printf("Account : Initial Balance: %f\n",account.getBalance()); companyThread.start(); bankThread.start(); try { companyThread.join(); bankThread.join(); System.out.printf("Account : Final Balance: %f\n",account.getBalance()); } catch (InterruptedException e) { e.printStackTrace(); } } }
标签:printf 方法 oid turn span 线程 his 开发 ace
原文地址:http://www.cnblogs.com/wzzkaifa/p/6829839.html