1 package com.iotec.synchronizedTest;
2
3 import java.io.ObjectInputStream;
4
5 public class BankDemo {
6 public static void main(String[] args) {
7 Bank bank = new Bank();
8 BankThread p1 = new BankThread(bank);
9 p1.start(); //櫃檯取錢
10 BankThread p2 = new BankThread(bank);
11 p2.start(); //ATM機上取錢
12
13 }
14 }
15
16 class BankThread extends Thread{
17 private Bank bank = null;
18 public BankThread(Bank bank){
19 this.bank = bank;
20 }
21
22 @Override
23 public void run() {
24 System.out.println(Thread.currentThread().getName()+"取錢:"+bank.getMoney(400));
25 }
26 }
27
28 class Bank {
29 //把競爭訪問的資源標識爲private
30 private int money = 500;
31
32 private Object object = new Object();
33 //取錢的方法,返回取錢的數目
34 //當一個線程去調用同步方法的時候,這個線程就得到當前對象的鎖
35 //其它線程當調用同步方法的時候只能等待,由於沒法獲取對象的鎖
36 //只有第一個線程釋放對象的鎖方可進入
37 /* public synchronized int getMoney(int number){
38 if(number<0){
39 return -1;
40 }else if(money<0){
41 return -2;
42 }else if(number-money>0){
43 return -3;
44 }else {
45 try {
46 Thread.sleep(1000); //模擬取錢的時間
47 } catch (InterruptedException e) {
48 e.printStackTrace();
49 }
50 money -= number;
51 System.out.println("餘額:"+money);
52 }
53 return number;
54 }*/
55 public synchronized int getMoney(int number){
56 // synchronized (this){
57 //能夠持有的是任何對象
58 synchronized (object){
59 if(number<0){
60 return -1;
61 }else if(money<0){
62 return -2;
63 }else if(number-money>0){
64 return -3;
65 }else {
66 try {
67 Thread.sleep(1000); //模擬取錢的時間
68 } catch (InterruptedException e) {
69 e.printStackTrace();
70 }
71 money -= number;
72 System.out.println("餘額:"+money);
73 }
74 return number;
75 }
76
77 }
78 /* public synchronized int getMoney(int number){
79
80 if(number<0){
81 return -1;
82 }else if(money<0){
83 return -2;
84 }else if(number-money>0){
85 return -3;
86 }else {
87 //放在這裏是不對的,由於等第一個線程執行完,第二個線程對上面的邏輯並不會進行判斷
88 //因此須要考慮清楚須要同步的是哪個代碼塊
89 synchronized (this){
90 try {
91 Thread.sleep(1000); //模擬取錢的時間
92 } catch (InterruptedException e) {
93 e.printStackTrace();
94 }
95 money -= number;
96 System.out.println("餘額:"+money);
97 }
98 }
99 return number;
100 }*/
101
102 }