i don’t really know how to describe it, so i’ll just post the whole thing. Your help would be greatly appreciated..thanks in advance
The initial balance value is $5000. The payroll thread adds $1000 to the balance each time.
The withdraw thread deducts $60 each time.
To make the race condition more obvious and interesting, the payroll is activated for 5 times,
and the withdraw is activated for 30 times.
First, compile the code. Then run it for 10 times.
Record the result of the final balance you see in each execution (so you should write down 10 numbers).
Are they consistent? What is the correct final balance? Explain the reason behind the phenomenon.
class SharedData {
private int balance=5000;
public int getBalance() {
return balance;
}
public void setBalance (int bal) {
balance = bal;
}
}
class Payroll implements Runnable
{
private SharedData sd;
public Payroll (SharedData sd) {
this.sd = sd;
}
public void run() {
int balance=sd.getBalance();
System.out.println(“Inside payroll, balance is “+balance);
try {
Thread.sleep((int)(Math.random()*10 ));
} catch (InterruptedException e) { }
sd.setBalance (balance+1000);
System.out.println(“Inside payroll: New balance is “+sd.getBalance());
}
}
class Withdraw implements Runnable
{
private SharedData sd;
public Withdraw (SharedData sd) {
this.sd = sd;
}
public void run() {
int balance=sd.getBalance();
System.out.println(“Inside withdraw, balance is “+balance);
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
sd.setBalance (balance-60);
System.out.println(“Inside withdraw: New balance is “+sd.getBalance());
}
}
class lab3_multi
{
public static void main (String arg[]) {
SharedData sd = new SharedData();
Payroll[] payrolls = new Payroll [5];
Thread[] payTh = new Thread [5];
Withdraw[] withdraws = new Withdraw [30];
Thread[] wdTh = new Thread [30];
for (int i=0; i<5; i++){
payrolls[i]= new Payroll(sd);
payTh[i]= new Thread (payrolls [i] );
}
for (int j=0; j<30; j++){
withdraws[j]=new Withdraw(sd);
wdTh[j]= new Thread (withdraws[j]);
}
for (int i=0; i<5; i++) {
payTh[i].start();
}
for (int j=0; j<30; j++) {
wdTh[j].start();
}
}
part 1:
Use Java Synchronization to avoid the race condition presented in the code.
part 2:
Use semaphore approach for this problem.
part 3:
Modify the code so that only one payroll thread and one withdraw thread are launched.
Then use Peterson’s solution for mutual exclusion between the payroll and withdraw threads.