用java使用同步方法、同步代码块和ReentrantLock可重入锁(任选两种办法)解决第二问中的线程同步问题
时间: 2024-03-05 16:54:50 浏览: 32
好的,针对第二个问题的线程同步问题,我们可以使用同步方法和ReentrantLock可重入锁两种方式来解决。
### 1. 同步方法
使用同步方法可以保证在同一时刻只有一个线程能够访问被synchronized关键字修饰的方法。在本例中,我们可以将withdraw和deposit方法都声明为同步方法,如下所示:
```java
public synchronized void withdraw(double amount){
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdraws " + amount + ", balance is " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " withdraws failed, balance is " + balance);
}
}
public synchronized void deposit(double amount){
if (amount > 0) {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposits " + amount + ", balance is " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " deposits failed, balance is " + balance);
}
}
```
### 2. ReentrantLock可重入锁
ReentrantLock可重入锁是一种更加灵活的线程同步方式,它比synchronized关键字提供了更多的功能,如公平锁、可中断锁、多条件变量等。在本例中,我们可以使用ReentrantLock来保证在同一时刻只有一个线程能够访问被锁住的代码块。具体实现如下:
```java
private final ReentrantLock lock = new ReentrantLock();
public void withdraw(double amount){
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdraws " + amount + ", balance is " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " withdraws failed, balance is " + balance);
}
} finally {
lock.unlock();
}
}
public void deposit(double amount){
lock.lock();
try {
if (amount > 0) {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposits " + amount + ", balance is " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " deposits failed, balance is " + balance);
}
} finally {
lock.unlock();
}
}
```
在以上代码中,我们使用了ReentrantLock的lock()和unlock()方法来手动加锁和解锁代码块。使用try-finally语句块的方式可以确保即使在代码块执行过程中出现异常,锁也能够被正确释放。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)