1

My program is not returning the expected output, I tried very hard but I don't know how to do for this code. What can I do ?

Expected output

1 2 3 4 5 6 7 8 ......2000

Actual output

1 2 3 4 5 6 1 2 3 4 5 6 ..1000

Main

public class Race_ConditonTest {

    public static void main(String[] args) {

        Race_Condition2 R1 = new Race_Condition2();
        Race_Condition2 R2 = new Race_Condition2();

        R1.start();
        R2.start();


   }
}

RaceCondition2 (sub class)

public class Race_Condition2 extends Thread{

    Race_Condition R= new Race_Condition();

    public void run() {
       R.sum();
    }   
}

RaceCondition class (super class)

public class Race_Condition  {
   int x=0;

   public int Load(int x){
       return x;
   }

    public void Store(int data) {
      int x= data;
      System.out.println(x);
    }

    public int Add(int i,int j) {
       return i+j ;
    }

    public void sum() {
       for (int i=0 ; i<1000 ; i++) { 
           this.x=Load(x);
           this.x=Add(x,1);
           Store(x);        
       }
    }
}
Bentaye
  • 9,403
  • 5
  • 32
  • 45
yoon
  • 33
  • 7

2 Answers2

0

how can i share x ?

simple way> make x static.

...

static int x=0;

... Edit

After some tests, if you find something weird happening then make the Store function synchronized.

  public synchronized void Store(int data) {
      int x= data;
      System.out.println(x);
    }

check out how synchronized work synchronized

MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
0

If your goal is to make the attribute x shared between R1 and R2 you could make it static in the RaceCondition class.

static int x=0;

Take care that if x is shared, they will be concurrent access to it, so some weird output could produce. Make the function that access x synchronized (as described here) :

// static cause it only access a static field
// synchronized so the access the the shared resource is managed
public static synchronized void sum() {
   for (int i=0 ; i<1000 ; i++) { 
       this.x=Load(x);
       this.x=Add(x,1);
       Store(x);        
   }
}

You should probably make the same changes on the other functions.

vincrichaud
  • 2,218
  • 17
  • 34