Question

In: Computer Science

I am tasked with creating a Java application that used 2 synchronized threads to calculate monthly...

I am tasked with creating a Java application that used 2 synchronized threads to calculate monthly interest and update the account balance

This is the parameters for reference to the code. Create a class AccountSavings. The class has two instance variables: a double variable to keep annual interest rate and a double variable to keep savings balance. The annual interest rate is 5.3 and savings balance is $100.
• Create a method to calculate monthly interest. • Create a method to run two threads. Use anonymous classes to create these threads. The first thread calls the monthly interest calculation method 12 times, and then displays the savings balance (the balance in 12th month). After that, this thread sleeps 5 seconds. The second thread calls the monthly interest calculation method 12 times, and then displays the savings balance (the balance in 12th month). Before the main thread ends, these two threads must be completed. • Add your main method into the same class and test your threads. After these two threads are executed, the savings balance must remain same

I am getting an error when calling monthlyInterest method inside my runThread method. non-static method monthlyInterest() cannot be referenced from a static context and I cant seem to figure out how to fix the issue.


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();
  
    }

}

Solutions

Expert Solution

Object:- To correct the program, check the flow and organise answer.

Solution:-


import static java.lang.Thread.sleep;

public class AccountSavings {

static double annualInterest=5.3;
static double savings=100.00;
static double balance = 0;
  
public static double monthlyInterest(double bal){
double monthlyRate;
monthlyRate = annualInterest/12;
if (bal == 0)
balance+=savings*monthlyRate;
else
bal+=savings*monthlyRate;
return bal==0?balance:bal;
}
  
public synchronized static void runThread(){
  
Thread 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(0));
}
}
};
  
  
Thread t2= new Thread(){
AccountSavings accountSavings=new AccountSavings();
@Override
public void run(){
try{sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
for(int i=1;i<13;i++){
System.out.println("Balance after " + i + " month: " + monthlyInterest(balance));
}
}
};
  
t1.start();
t2.start();
  
}

public static void main(String[] args){
  
runThread();
  
}

}

Note: 1:- Never call non static variable from static methods (make static variables or go for singleton structure).

2:- No need to sleep in first run just put it inside at the begining of second run.

3:- Pass balance parameter in monthlyInterest method so that we can achieve the desired single method functionality.

4:- Compile this code using "javac classname.java" and then run this code using "java classname" if you are not using any editor tool like netbeans or eclips.


Related Solutions

Implement a solution java solution for creating two writer threads and four reader threads
Implement a solution java solution for creating two writer threads and four reader threads
Create a Java application that will exhibit concurrency concepts. Your application should create two threads that will act as counters.
JAVACreate a Java application that will exhibit concurrency concepts. Your application should create two threads that will act as counters. One thread should count up to 20. Once thread one reaches 20, then a second thread should be used to count down to 0.
Scenario: I am creating a course for inclusion into an established nursing curriculum. I am supposed...
Scenario: I am creating a course for inclusion into an established nursing curriculum. I am supposed to describe the program level of the course am proposing. What do they mean by program level? This is a hypothetical community college with a two year nursing program.
I am working on creating a Broadcast Receiver. I am extremely new to Android development and...
I am working on creating a Broadcast Receiver. I am extremely new to Android development and Java. I added my code at the bottom. Whenever I press the button the app crashes. I'm assuming something is wrong with connecting the broadcastIntent() function. I appreciate any help :) Here are the directions from my professor: Create an empty project Create a method in MainActivity.java which creates a Broadcast. public void broadcastIntent(View view){        Intent intent = new Intent();        intent.setAction("my.CUSTOM_INTENT"); sendBroadcast(intent);...
I am working on creating a Broadcast Receiver. I am extremely new to Android development and...
I am working on creating a Broadcast Receiver. I am extremely new to Android development and Java. I added my code at the bottom of this, but whenever I press the button the app crashes. I'm assuming something is wrong with connecting the broadcastIntent() function. If you could really focus on the first part that would be great!! I appreciate any help :) Here are the directions from my professor: Create an empty project Create a method in MainActivity.java which...
I am creating SAS code, but am receiving an errors " ERROR: Value is out of...
I am creating SAS code, but am receiving an errors " ERROR: Value is out of range or inappropriate. ERROR: No body file. HTML5(WEB) output will not be created." This is the code: option ls=65 ps=65; data one; input IQ; cards; 145 139 122 ; title 'Normal Quantile - Quantile Plot for IQ'; ods graphics on; proc univariate data=one; qqplot IQ / normal (mu=est sigma=est); run;
I am using Java and what do you mean samples? Creation of Program Application (Development Task...
I am using Java and what do you mean samples? Creation of Program Application (Development Task 2) This program should use a class file you create called: SavingsAccount. This class file should store the following information: Annual Interest Rate (this can be hardcoded) Starting Balance (use a constructor to accept this information) Create method to add all Deposits from Deposits.txt file. Create method to subtract all Withdrawals from Withdrawals.txt file. Create method to calculate the interest rate which is the...
How to graph: I am tasked to graph a Beer-Lambert of BPB. It is explained that...
How to graph: I am tasked to graph a Beer-Lambert of BPB. It is explained that BPB that has it a molar extinction coefficient of basic form BPB is 31100M^-1cm^-1 at 590nm. Cuvette pathlength is 1cm. It transferred about 1ml of BPB solution into the cuvette for test and record. It was then made a serious of dilutions with 1 to 2, 1 to 4, 1 to 10, 1 to 20, and 1 to 40. They were tested and recorded...
Create a project plan on the game or application you are creating. Using java programming. The...
Create a project plan on the game or application you are creating. Using java programming. The project plan should include the following: A description of the game or application The IDE or game engine your plan to use to create the game or app and information on how you are going to develop the game or app If you choose to create a game, how are you going to approach the game design and game development process or if you...
I am using NetBeans IDE Java to code and I am seeking comment to the code...
I am using NetBeans IDE Java to code and I am seeking comment to the code as well (for better understanding). Magic squares. An n x n matrix that is filled with the numbers 1, 2, 3, …, n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. Write a program that reads in 16 values from the keyboard, displays them in a 4...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT