传统的多线程操作数字处理的时候,会出现同步问题,导致计算结果不正确。
/**
* @author qx
* @date 2023-04-23
* @Descripion: 传统多线程计算存款金额
*/
public class Test4 {
// 存款金额
private static int money = 0;
public static void main(String[] args) throws Exception {
// 待存款金额
int[] data = {1000, 2000, 3000};
for (int temp : data) {
// 创建多个线程处理
new Thread(() -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 累加金额
money += temp;
}).start();
}
TimeUnit.SECONDS.sleep(1);
System.out.println("存款总额为:" + money);
}
}
执行结果:
存款总额为:1000
为了解决这个问题,java提供了原子操作类处理这类问题。现在使用AtomicInteger的同步机制处理存款金额的问题。
/**
* @author qx
* @date 2023-04-23
* @Descripion: 使用原子操作类解决数据同步问题
*/
public class Test5 {
// 存款总额
private static AtomicInteger money = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
// 待存款金额
int[] data = {1000,2000,3000};
for (int temp : data) {
// 创建多个线程处理
new Thread(()->{
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 金额累加
money.addAndGet(temp);
}).start();
}
TimeUnit.SECONDS.sleep(1);
System.out.println("存款总额为:"+money);
}
}
执行结果:
存款总额为:6000