并发:使用未同步的方法更改变量

时间:2016-11-27 20:20:58

标签: java multithreading concurrency thread-safety

以此SELECT m.id, m.user_id AS msg_owner, o.name AS msg_owner_name, m.sender_user_id, s.name, m.recipient_user_id, r.name AS recipient_name, m.body, m.created_at FROM messages m JOIN users o ON m.user_id = o.id JOIN users s ON m.sender_user_id = s.id JOIN users r ON m.recipient_user_id = r.id 类定义为例:

ConcurrentDouble

现在如果我做了以下,

public class ConcurrentDouble {

  public double num = 0;

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

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

我们知道号码从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 } } 开始,我们预计最后会有0。该号码可能会变为0-5.0吗?

1 个答案:

答案 0 :(得分:3)

是的,这是可能的。 -=+=不是原子操作。即使这样,JVM也不能保证对double的写入是原子的。