gpt4 book ai didi

java - 将 Await、Signal、SignalAll 替换为 wait、notify 和 notifyAll

转载 作者:行者123 更新时间:2023-12-01 12:55:51 25 4
gpt4 key购买 nike

我想用 wait(),notifyAll() (java 的默认监视器)替换 wait(),signalAll() 和下面列出的我的代码,问题是一旦线程进入等待状态。它永远不会再被通知..感谢您的帮助。

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AccountThreadCommunicationDefault {
private static Account account = new Account();
private static Random random = new Random();
public static void main(String... args) {
ExecutorService es = Executors.newFixedThreadPool(2);
es.execute(new WithdrawTask());
es.execute(new DepositTask());
es.shutdown();
}

private static class WithdrawTask implements Runnable {
public void run() {
while (true) {
account.withdraw(random.nextInt(600));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

private static class DepositTask implements Runnable {
public void run() {
while (true) {
account.deposit(random.nextInt(500));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

private static class Account {
private Integer balance = 500;
private static Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// private Object object = new Object();

// public synchronized void deposit(int count) {
public void deposit(int count) {
try {
lock.lock();
System.out.print("当前账户余额:" + balance);
balance += count;
System.out.println(" 存款:" + count + " 账户余额(deposit): "
+ getBalance());
// synchronized (object) {
// object.notifyAll();
// }
synchronized (this) {
this.notify();
}
} catch (IllegalMonitorStateException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}

public void withdraw(int count) {
try {
lock.lock();
while (balance < count) {

System.out.println("余额不足:" + getBalance() + " 等待存款..");
// synchronized (object) {
// object.wait();
// }
synchronized (this) {
this.wait();
}

System.out.print("当前账户余额:" + balance);
balance -= count;
System.out.println(" 取现:" + count + " 账户余额(withdraw): "
+ getBalance());
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}

public int getBalance() {
return this.balance;
}
}

}

最佳答案

你陷入了僵局。 Withdraw 任务正在等待 Account 对象的监视器,同时保持 ReentrantLock 锁定。 Deposit 任务无法notify() Account 对象监视器,因为它无法锁定ReentrantLock。

您需要 wait() 和 notification() 用作互斥体的同一个对象。无论是 ReentrantLock 还是 Account 对象的监视器都没有关系。但它不会像你用两个不同的锁编写的那样工作。

关于java - 将 Await、Signal、SignalAll 替换为 wait、notify 和 notifyAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com