java - 如何修改显示数据损坏问题的代码
问题描述
我目前正在开展一个项目,该项目向我展示了数据损坏问题的样子。下面给出的代码 ( What is balance? 4
) 的输出不正确,因为一个任务覆盖了另一个任务。我想知道如何重写代码以使余额始终为 100。
import java.util.concurrent.*;
public class AccountWithoutSync {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool(); //create thread pool
// Create and launch 100 threads
for (int i = 0; i < 100; i++) {
executor.execute(new AddAPennyTask());
}
executor.shutdown();
// Wait until all tasks are finished
while (!executor.isTerminated()) {
}
System.out.println("What is balance? " + account.getBalance());
}
// A thread for adding a penny to the account
private static class AddAPennyTask implements Runnable {
public void run() {
account.deposit(1);
}
}
// An inner class for account
private static class Account {
private int balance = 0;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
int newBalance = balance + amount;
// This delay is deliberately added to magnify the
// data-corruption problem and make it easy to see.
try {
Thread.sleep(5);
}
catch (InterruptedException ex) {
}
balance = newBalance;
}
}
}
解决方案
推荐阅读
- apache-spark - Spark 作业状态正在运行,但第一步启动的时间几乎是 20 分钟后
- r - 使用 purrr 重命名 tibbles 列表中的不同列
- sharepoint - 更改 AD 后从用户信息列表中删除用户
- java - 在 R 3.6 上为 ubuntu 仿生海狸安装 rJava 时出现“无法运行简单的 JNI 程序”错误消息
- ios - ReactiveSwift 中 flatmap 策略之间的差异
- javascript - 如何用工厂函数组织Vue单元测试?
- grails - 禁用 Grails 4 加载文本
- matlab - 从 Matlab 中预先指定的概率质量函数中绘制随机数
- ios - swift facebook sdk注销功能不起作用
- c# - 如何在图片框中显示来自访问数据库的附件图像