Skip to content

Commit 74b98e7

Browse files
committed
提交synchronized
1 parent acabaab commit 74b98e7

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.concurrency.synchronize;
2+
3+
4+
public class Account {
5+
private double balance = 0.0f;
6+
7+
public double getBalance() {
8+
return balance;
9+
}
10+
11+
public void setBalance(double balance) {
12+
this.balance = balance;
13+
}
14+
15+
public synchronized void addAmount(double amount){
16+
double tmp = balance;
17+
try {
18+
Thread.sleep(10);
19+
} catch (InterruptedException e) {
20+
e.printStackTrace();
21+
};
22+
tmp += amount;
23+
balance = tmp;
24+
}
25+
26+
public synchronized void SubtractAmount(double amount){
27+
double tmp = balance;
28+
try {
29+
Thread.sleep(10);
30+
} catch (InterruptedException e) {
31+
e.printStackTrace();
32+
};
33+
tmp -= amount;
34+
balance = tmp;
35+
}
36+
37+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.concurrency.synchronize;
2+
3+
public class Bank implements Runnable{
4+
5+
private Account account;
6+
7+
public Bank(Account account){
8+
this.account = account;
9+
}
10+
11+
@Override
12+
public void run() {
13+
for(int i = 0 ; i < 100 ; i++){
14+
account.SubtractAmount((double)1000);
15+
System.out.println("Company subtract account : 1000 , the balance : " + account.getBalance() );
16+
}
17+
}
18+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.concurrency.synchronize;
2+
3+
public class Company implements Runnable{
4+
5+
private Account account;
6+
7+
public Company(Account account){
8+
this.account = account;
9+
}
10+
11+
@Override
12+
public void run() {
13+
for(int i = 0 ; i < 99 ; i++){
14+
account.addAmount(1000);
15+
System.out.println("Company add account : 1000 , the balance : " + account.getBalance() );
16+
}
17+
}
18+
19+
}

0 commit comments

Comments
 (0)