【发布时间】:2014-08-13 10:27:03
【问题描述】:
我目前正在阅读 Java 中的 Threads 并使用 wait() 和 notifyAll() 方法。我试图通过编写一个实际示例来理解这一点,但我没有得到想要的输出。
简而言之,以下是对我的代码的解释: 该程序模拟一个简单的工作情况。也就是说,您的余额从零开始,每小时增加 15 美元(或其他货币)。当余额低于 100 时,程序应该开始工作,直到余额超过该目标。因此,程序应该开始工作,计算小时数。一旦余额达到/超过 100,您就完成了工作,程序应该终止。代码由三个类组成,Shared(保存共享数据和同步方法)Hours和Money,其中最后两个是Thread的子类.
考虑到这种情况,这个人应该工作 7 个小时,直到赚到 > 100 美元。
代码
class Shared {
int hourSalary = 15;
int numHours = 0;
int balance;
/* Method handling balance checks */
public synchronized void earnMoney() {
//As long as you have not earned 100 dollars
while((numHours * 15) < 100) {
try {
wait(); //Wait for balance to increase
}
catch(InterruptedException e) {
return;
}
}
//balance += hourSalary; //Increment by 15 after each hour
balance = hourSalary * numHours; //Incorrect, but stops the code at the right time!
System.out.println("You have now worked " + numHours + " hours and increased your balance. Dollars earned so far " + balance);
notifyAll();
}
/* Method handling work hours */
public synchronized void startWorking() {
while(balance > 100) {
try {
wait();
}
catch(InterruptedException e) {
return;
}
}
numHours++;
System.out.println("You have worked " + numHours + " hours and earned " + balance + " dollars.");
notifyAll();
}
public synchronized boolean enoughMoney() {
return balance > 100; //Enough money when over 100 dollars
}
public synchronized boolean enoughWork() {
return enoughMoney(); //Stop working when enough money
}
}
对于 Hours 和 Money 类,run() 方法如下:
//run-method for the class Money
public void run() {
while(!object.enoughMoney()) {
object.earnMoney();
try {
sleep(1000); // 1 second
}
catch(InterruptedException e) {
return;
}
}//end while
}//end run
和
//run-method for the class Hours
public void run() {
while(!object.enoughWork()) {
object.startWorking();
try {
sleep(1000); // 1 second
}
catch(InterruptedException e) {
return;
}
}//end while
}//end run
现在,当运行此代码时,程序会在适当的时刻终止,此时已赚了 105 美元。但是,运行时提供的输出不正确。在达到目标之前,它不会根据工作时间更新余额:
你工作了 1 小时,赚了 0 美元。
你工作了 2 个小时,赚了 0 美元。
你工作了 3 个小时,赚了 0 美元。
你工作了 4 小时,赚了 0 美元。
你工作了 5 个小时,赚了 0 美元。
你工作了 6 个小时,赚了 0 美元。
你工作了 7 个小时,赚了 0 美元。
您现在已经工作了 7 个小时,余额有所增加。到目前为止赚取的美元 105
任何帮助/提示/技巧/等。非常感谢如何解决这个问题:)
【问题讨论】:
标签: java multithreading wait synchronized notify