标签:style io 使用 java ar for 数据 art sp
在多线程开发中,总会遇到多个在不同线程中的方法操作同一个数据,这样在不同线程中操作这个数据不同的顺序
或者时机会导致各种不同的现象发生,以至于不能实现你预期的效果,不能实现一致性,这时候就可以使用
synchronized关键字对一个方法来说,这个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(); } } }
标签:style io 使用 java ar for 数据 art sp
原文地址:http://blog.csdn.net/a352193394/article/details/39379303