Trương Quang Dũng
Trương Quang Dũng

Reputation: 29

Synchronized Thread in Java

I have 3 class like this:

Source.java

public class Source extends Thread{
    private int x= 0;
    public void increment(int id){
          x++;
          System.out.println(id+" "+x);
    }
}

Task.java

public class Task extends Thread{
      private Source source;
      private int id;
      public Task(Source source, int id){
            this.source=source;
            this.id=id;
      }
      public void run(){
             for (int i=0;i<100;i++){ 
                 try{Thread.sleep(1000);}catch(InterruptedException e){}
                 source.inc(id);
             }
      }
}

Main.java

public class Main{
      public static void main(String[] args) throws IOException{
             Source source = new Source();
             Task t1=new Task(source,1);
             Task t2=new Task(source,2);
             t1.start();
             t2.start();
      }
}

I want when the x of the class Source will be equal to 4 only one task continues to increment x until x is equal to 8, we return to normal. The result will look like this:

1 1
2 2
1 3
2 4
1 5
1 6
1 7
1 8
1 9
1 10
2 11
1 12
2 13
...

How do I modify the code to achieve the desired result?

Upvotes: 0

Views: 103

Answers (1)

Vml11
Vml11

Reputation: 534

Basically you have two threads that modify the same variable x. There is no garantee about the order of execution. You should synchronize.

With your current implementation you may face a problem (The race condition problem): Race condition example

Something like this is an scenario that most likely is going to happen to you:

....
1 3
2 4
2 5
1 6
1 7
2 7
1 8
2 9
1 10
2 10
...

As you can see the thread 2 (source 2) tries to increment the variable x when the variable has been already incremented but the value it has to increment is the old one.

x = 0

  1. Thread 1 reads the variable x (0)
  2. Thread 2 reads the variable x (0)
  3. Thread 1 increments variable x + 1 (0 + 1) = 1
  4. Thread 2 increments variable x + 1 (0 + 1) = 1

In order to solve this you need to synchronize your variable, an AtomicInteger would be enough. + I don't think you need the extends Thread on your Source class, you can get rid of it

Upvotes: 1

Related Questions