简体   繁体   English

我有 2 个并发数据结构,我想以原子方式更新它们

[英]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.

相关问题 并发和并发数据结构 - Concurrency and Concurrent Data Structures 我有一个不想更新的JLabel - I have a JLabel that doesn't want to update 我需要将数据保存在 mongodb 中,然后以原子方式将这些数据发送到 kafka - I need to save data in mongodb and send this data to kafka all atomically 使用并发数据结构的示例? - Examples for uses of concurrent data structures? 如何从数据库表中获取数据并将数据更新到休眠中的另一个表中? 我已经在JSP中完成了,但是我想在Hibernate中完成 - How to get data from database table and update that data into another table in hibernate? I have done it in JSP but i want to do in Hibernate 在 JavaFX 我想要一个按钮 appendText 并更新 ArrayList - In JavaFX I want to have a button appendText and update an ArrayList 我想在jtable中计算数据,但出现错误[Java] - I want to calculate data in jtable but i have a error [Java] 我只想要一个用于所有活动的自定义工具栏 我尝试了许多解决方案,但没有一个奏效 - I want only one custom Toolbar for all activities I have tried many solutions but none of them worked java,Webdriver,我想获取网页中的所有链接,然后将它们与我拥有的字符串名称进行比较,如果找到它,则单击它 - java,Webdriver, I want to fetch all links in a webpage and then compare them to a string name that I have and if it is found then click it 阻塞行为-并发数据结构Java - Blocking Behaviour - Concurrent Data Structures Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM