File tree Expand file tree Collapse file tree 3 files changed +74
-0
lines changed
javaConcurrency/src/com/concurrency/synchronize Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments