简体   繁体   中英

Concurrency: Changing a variable with unsynchronized methods

Take this ConcurrentDouble class definition as an example:

public class ConcurrentDouble {

  public double num = 0;

  public void subtract(double num) { 
    this.num -= num; 
  }

  public void add(double num) { 
    this.num += num; 
  }
}

Now if I did the following,

public class Test {
  public static void main(String[] args) {
    ConcurrentDouble d1 = new ConcurrentDouble();

    Thread one = new Thread(() -> { d1.add(5); }).start();
    Thread two = new Thread(() -> { d1.subtract(5); }).start();

    one.join();
    two.join();

    System.out.println(d1.num); // <-- OUTPUT
  }
}

We know the number starts off at 0 , and we expect it to have 0 at the end. Is it possible that the number becomes -5.0 or 5.0 ?

Yes, it's possible. -= and += are not atomic operations. And even then, the JVM doesn't guarantee that a write to a double is atomic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM