[英]I have a 2 concurrent data structures and I want to update them atomically
How to make sure that these two concurrent data structure statements get executed as an atomic block without using synchronized
statement so that the sum is consistent at any given point in time?如何确保这两个并发数据结构语句在不使用
synchronized
语句的情况下作为原子块执行,以便总和在任何给定时间点保持一致?
Note : I am new to multi-threading in java.注意:我是 Java 多线程的新手。
AtomicLong sumOfAllItems=new AtomicLong();
AtomicLong itemSpecificSum=new AtomicLong();
public void addPrice(long price){
// how to make sure that these two statements get executed
// with synchronised() block
sumOfAllItems.addAndGet(price);
itemSpecificSum.addAndGet(price);
}
Change your method from this:从此更改您的方法:
public void addPrice(long price) {
// ...
}
to this:对此:
public synchronized void addPrice(long price) {
// ...
}
By designating the method as sychronized
, the JVM will allow no more than one thread at a time to execute that method.通过将方法指定为
sychronized
,JVM 将一次只允许一个线程执行该方法。
There are other ways of writing thread safe code, but unless and until you have a specific reason to use them, using synchronized it great – it's simple, correct, and easy to understand / reason about.还有其他编写线程安全代码的方法,但是除非您有特定的理由使用它们,否则使用 synchronized 会很棒——它简单、正确且易于理解/推理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.