-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBankSimpleTest.java
More file actions
58 lines (50 loc) · 1.45 KB
/
BankSimpleTest.java
File metadata and controls
58 lines (50 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package org.cp;
/**
* create by CP on 2019/7/26 0026.
*/
public class BankSimpleTest {
public static void main(String[] args) {
Account account = new Account();
Customer customer1 = new Customer(account);
Customer customer2 = new Customer(account);
customer1.setName("客户1");
customer2.setName("客户2");
customer1.start();
customer2.start();
}
}
class Account {
private Double balance=0.0;//余额
Double getBalance() {
return balance;
}
void setBalance(Double balance) {
this.balance = balance;
}
}
class Customer extends Thread{
private final Account account;
Customer(Account account) {
this.account = account;
}
private void deposit(Double amount) {
synchronized (account) {//锁定操作同步数据的代码块,让一次只能一个客户进来操作
Double balance = account.getBalance();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Double newBalance = balance+amount;
account.setBalance(newBalance);
System.out.println(Thread.currentThread().getName()+"存入 "+amount
+" 元, 现在余额为: "+newBalance +" 元");
}
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
deposit(1000.0);
}
}
}