1
+ package sporadic .thread ;
2
+
3
+ public class HusbandAndWifeJob implements Runnable {
4
+
5
+ /*
6
+ * (non-Javadoc)
7
+ *
8
+ * @see java.lang.Runnable#run()
9
+ */
10
+ @ Override
11
+ public void run () {
12
+ for (int i = 0 ; i < 10 ; i ++) {
13
+ makeWithdrawl (10 );
14
+ if (bankAccount .getBalance () < 0 ) {
15
+ System .out .println ("Overdrawn!!!" );
16
+ }
17
+ }
18
+ }
19
+
20
+ private BankAccount bankAccount = new BankAccount ();
21
+
22
+ /**synchronized is the key here to let one thread finish, and then let the other thread to kick in.
23
+ * Without synchronized this keyword, two threads will invoke this method randomly based on how the OS
24
+ * scheduler schedules it.*/
25
+ private synchronized void makeWithdrawl (int amount ) {
26
+ if (bankAccount .getBalance () >= amount ) {
27
+ System .out .println (Thread .currentThread ().getName () + " is about to withdraw: " + amount );
28
+ try {
29
+ System .out .println (Thread .currentThread ().getName () + " is going to sleep." );
30
+ Thread .sleep (1000 );
31
+ } catch (InterruptedException e ) {
32
+ e .printStackTrace ();
33
+ }
34
+ System .out .println (Thread .currentThread ().getName () + " woke up." );
35
+ bankAccount .withdraw (amount );
36
+ System .out .println (Thread .currentThread ().getName () + " finished withdrawl: " + amount + "\t now the balance is: " + bankAccount .getBalance ());
37
+ } else {
38
+ System .out .println ("Sorry, not enough balance for " + Thread .currentThread ().getName ());
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param args
44
+ */
45
+ public static void main (String [] args ) {
46
+ HusbandAndWifeJob husbandAndWifeJob = new HusbandAndWifeJob ();
47
+ Thread husband = new Thread (husbandAndWifeJob );
48
+ Thread wife = new Thread (husbandAndWifeJob );
49
+ husband .setName ("Steve Sun" );
50
+ wife .setName ("Sophie Yan" );
51
+ wife .start ();
52
+ husband .start ();
53
+ System .out .println ("Program ended.\n \n \n \n \n \n " );
54
+ }
55
+
56
+ }
57
+
58
+ class BankAccount {
59
+ private int balance = 100000 ;
60
+
61
+ public int getBalance () {
62
+ return balance ;
63
+ }
64
+
65
+ public void withdraw (int withdrawAmount ) {
66
+ balance = balance - withdrawAmount ;
67
+ }
68
+ }
0 commit comments