【发布时间】:2019-11-14 14:38:30
【问题描述】:
这是代码参考的参数。
创建一个类 AccountSavings。该类有两个实例变量:一个保持年利率的双变量和一个保持储蓄平衡的双变量。年利率为 5.3,储蓄余额为 100 美元。
• 创建计算每月利息的方法。
• 创建一个运行两个线程的方法。使用匿名类来创建这些线程。第一个线程调用每月利息计算方法12次,然后显示储蓄余额(第12个月的余额)。之后,该线程休眠 5 秒。第二个线程调用每月利息计算方法12次,然后显示储蓄余额(第12个月的余额)。在主线程结束之前,这两个线程必须完成。
• 将您的主要方法添加到同一个类中并测试您的线程。这两个线程执行后,储蓄余额必须保持不变
在我的 runThread 方法中调用monthlyInterest 方法时出现错误。 不能从静态上下文引用非静态方法monthlyInterest() 我似乎无法弄清楚如何解决这个问题。
...
import static java.lang.Thread.sleep;
class AccountSavings {
double annualInterest=5.3;
double savings=100.00;
public void monthlyInterest(){
double monthlyRate;
monthlyRate = annualInterest/12;
double balance = 0;
balance+=savings*monthlyRate;
}
public synchronized static void runThread(){
Thread t1;
t1 = new Thread(){
AccountSavings accountSavings= new AccountSavings();
@Override
public void run(){
for(int i=1;i<13;i++){
System.out.println("Balance after " + i + "month: " + monthlyInterest());
}
try{sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
}
};
Thread t2= new Thread(){
AccountSavings accountSavings=new AccountSavings();
@Override
public void run(){
for(int i=1;i<13;i++){
System.out.println("Balance after " + i + " month: " + monthlyInterest(balance));
}
try{sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
}
};
t1.start();
t2.start();
}
public static void main(String[] args){
runThread();
}
}
【问题讨论】:
标签: java multithreading