forked from liujiboy/Java_Course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynAccount.java
More file actions
43 lines (36 loc) · 1.05 KB
/
SynAccount.java
File metadata and controls
43 lines (36 loc) · 1.05 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
package code0905;
public class SynAccount {
double balance;// 余额
final double MAX = 10000;// 最高限额
public SynAccount(double balance) {
this.balance = balance;
}
// 存款同步方法
public synchronized void withdraw(double money) {
if (balance < money) {
try {
System.out.printf("取款%1$,.2f失败。余额:%2$,.2f\n", money, balance);
wait();// 进入等待队列
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance -= money;
System.out.printf("取款%1$,.2f成功。余额:%2$,.2f\n", money, balance);
notify();// 唤醒等待队列的线程
}
// 取款同步方法
public synchronized void deposit(double money) {
if (balance + money >= MAX) {
try {
System.out.printf("存款%1$,.2f失败。余额:%2$,.2f\n", money, balance);
wait();// 进入等待队列
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance += money;
System.out.printf("存款%1$,.2f成功。余额:%2$,.2f\n", money, balance);
notify();// 唤醒等待队列的线程
}
}