Todo
1. 对比下 有无 synchronized的 运行结果, 就会发现 不同的线程 同时修改 同一个对象的某条属性 就会导致错乱。 因为某些线程修改的结果被覆盖了。
所以我们要加上 synchronized 来保证 互斥访问
```
class Account {
private String name;
private float amount;
public Account(String name, float amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public float getBalance() {
return amount;
}
public void deposit(float amt) {
float temp = amount;
temp -= amt;
try {
//模拟其它处理所需要的时间,比如刷新数据库等
Thread.sleep((int) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
amount = temp;
}
public void withdraw(float amt) {
float temp = amount;
temp += amt;
try {
Thread.sleep((int) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
amount = temp;
}
}
public class Bank {
private static int NUM_OF_THREAD = 1000;
static Thread[] threads = new Thread[NUM_OF_THREAD];
public static void main(String[] args) {
Account acc = new Account("Francis", 1000.0f);
for (int i = 0; i < NUM_OF_THREAD; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
acc.deposit(100.0f);
acc.withdraw(100.0f);
}
});
threads[i].start();
}
for (int i = 0; i < NUM_OF_THREAD; i++) {
try {
// 等待 所有线程运行结束
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(String.format("Finally, %s‘s balance is: %f", acc.getName(), acc.getBalance()));
}
}
```
```
class Account {
private String name;
private float amount;
public Account(String name, float amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public float getBalance() {
return amount;
}
public synchronized void deposit(float amt) {
float temp = amount;
temp -= amt;
try {
//模拟其它处理所需要的时间,比如刷新数据库等
Thread.sleep((int) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
amount = temp;
}
public synchronized void withdraw(float amt) {
float temp = amount;
temp += amt;
try {
Thread.sleep((int) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
amount = temp;
}
}
public class Bank {
private static int NUM_OF_THREAD = 1000;
static Thread[] threads = new Thread[NUM_OF_THREAD];
public static void main(String[] args) {
Account acc = new Account("Francis", 1000.0f);
for (int i = 0; i < NUM_OF_THREAD; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
acc.deposit(100.0f);
acc.withdraw(100.0f);
}
});
threads[i].start();
}
for (int i = 0; i < NUM_OF_THREAD; i++) {
try {
// 等待 所有线程运行结束
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(String.format("Finally, %s‘s balance is: %f", acc.getName(), acc.getBalance()));
}
}
```
原文:https://www.cnblogs.com/francis11h/p/11775937.html