This is the same code as a previous question I had asked but addressing a different issue. Essentially I am trying to make a bank account with two threads, each representing a user of the account. The users will deposit and withdraw 20$ from the account (randomly).
However, both these threads run in parallel, and the withdraw/deposit happen at the same time. I am trying to limit both threads such that it waits for the other thread to finish before executing its own run method.
Listed below is the code.
Thread creation class
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class BankAccount extends Thread{
public static double balance = 1000;
public String threadName;
BankAccount(String name){
threadName = name;
}
public void run(){
System.out.println(threadName + "account initiated.");
for(int i = 0; i < 10; i++){
try{
Random rand = new Random();
int num = rand.nextInt(2) + 1;
if(num == 1){
Thread.sleep(200); //0.2 seconds to deposit
System.out.println(threadName + " is depositing 20$ in the bank.");
balance += 20;
System.out.println("The new balance is " + balance + "dollars" );
}
else{
Thread.sleep(500); //half a second to withdraw
System.out.println(threadName + " is withdrawing 20$ from the bank.");
balance -= 20;
System.out.println("The new balance is " + balance + "dollars.");
}
}
catch(InterruptedException e){
System.out.println("Process terminated.");
}
}
}
}
Thread Driver Class
public class BankAccountSimDriver {
public static void main(String[] args){
Thread user1 = new BankAccountSIm("user1");
Thread user2 = new BankAccountSIm("user2");
user1.start();
user2.start();
}
}
The output currently:
user1 initiated.
user2 initiated.
user1 is depositing 20$ in the bank.
user2 is depositing 20$ in the bank.
The new balance is 1020.0 dollars
The new balance is 1040.0 dollars
user2 is depositing 20$ in the bank.
The new balance is 1060.0 dollars
user1 is withdrawing 20$ from the bank.
The new balance is 1040.0 dollars.
Currently, user1 and user2 run at the same time. I'd like to edit the code such that only one user can deposit/withdraw at a time (indicated by the sleep() time separation)
So the ideal output:
user1 initiated.
//wait 0.2 seconds
user1 is depositing 20$ in the bank.
The new balance is 1020.0 dollars
user2 initiated.
//wait 0.2 seconds
user2 is depositing 20$ in the bank.
The new balance is 1040.0 dollars
//wait 0.5 seconds
user1 is withdrawing 20$ from the bank.
The new balance is 1020.0 dollars.
...
Randominstance each time you use it. That kills its "random" characteristics. Instantiate it once and let it handle generating new values.InterruptedException.