forked from liujiboy/Java_Course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockAccount.java
More file actions
45 lines (36 loc) · 839 Bytes
/
LockAccount.java
File metadata and controls
45 lines (36 loc) · 839 Bytes
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
/**
*
*/
package code0905;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* ReLock.java Copyright (c) 2016 ChongQing University All rights reserved.
*/
public class LockAccount {
double balance;// 账号余额
Lock lock = new ReentrantLock();// 创建锁对象
public LockAccount(double balance) {
super();
this.balance = balance;
}
// 使用显示锁
public void withdraw(double money) {
lock.lock();// 锁定
try {
if (balance >= 1000) {
try {
Thread.sleep(100);
balance -= 1000;
System.out.println("取款1000成功。");
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("取款失败。");
}
} finally {
lock.unlock();// 释放锁
}
}
}