Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the following code in Java: create a shared integer TOTAL initialized to 5

ID: 3780712 • Letter: W

Question

Write the following code in Java: create a shared integer TOTAL initialized to 5. Create 2 methods that will modify the value of TOTAL, where first method increment Total, will increment total by 1, and second method, multiply Total, will multiply TOTAL by 2. Create and start 2 threads, where the first thread will invoke increment Total and second thread will invoke multiply Total. Run the code several times, what is the output result and is the same every time? Modify your code to provide competition synchronization such that race condition does not occur.

Explanation / Answer

package snippet;

public class Lab {
volatile int TOTAL=5;
  
void incrementTotal()
{
TOTAL=TOTAL+1;
}
  
void multiplyTotal()
{
TOTAL=TOTAL*2;
}
public void run() {

}
public static void main(String[] args) {
// TODO Auto-generated method stub
final Lab l=new Lab();
Thread t = new Thread(new Runnable() {
public void run() {
/*
* Do something
*/
l.incrementTotal();
}
});

  
Thread t1 = new Thread(new Runnable() {
public void run() {
/*
* Do something
*/
l.multiplyTotal();;
}
});
t.start();
t1.start();
  
  
System.out.println(l.TOTAL);
}

}

=============================================

when we run above code multiple times it gives result either 6,5,12 or 13.Output is not same all time.

==========================================================================

Complete syncronized code:

package snippet;

public class Lab {
   volatile int TOTAL=5;
  
   synchronized void incrementTotal()
   {
       TOTAL=TOTAL+1;
   }
  
   synchronized void multiplyTotal()
   {
       TOTAL=TOTAL*2;
   }
  
   public static void main(String[] args) throws InterruptedException {
       // TODO Auto-generated method stub
       final Lab l=new Lab();
       Thread t = new Thread(new Runnable() {
       public void run() {
           synchronized(this)
           {
           l.incrementTotal();
           }
       }
       });

      
       Thread t1 = new Thread(new Runnable() {
       public void run() {
       /*
       * Do something
       */
           synchronized(this)
           {
           l.multiplyTotal();
           }
       }
       });
       t.start();
       t1.start();
      
       t.join();
       t1.join();
       System.out.println(l.TOTAL);
   }

}

================

Output will same all time :

12