gpt4 book ai didi

java - 通过线程池运行可运行,我应该使用 volatile 吗?

转载 作者:行者123 更新时间:2023-11-30 06:58:41 26 4
gpt4 key购买 nike

就像下面的示例代码一样。

我将使用线程池来运行TestRunnable对象。

我应该将变量total声明为 volatile 吗?

public class TestRunnable implements Runnable {
private int total;
@Override
public void run() {
if (total > 10) {
return;
} else {
total += 1;
System.out.print("Run in times: " + total);
}
}
}

最佳答案

假设您的变量被声明为

 private int total;

(非静态)

它不会在多个线程之间共享(只要不断为每个提交的线程创建新实例),因此无需将其声明为 volatile。

如果您多次使用同一个实例 - 那么您应该考虑使用 AtomicInteger 而不是常规的 int,因为操作

total+= 1;

total++;

不是原子操作,这可能会导致多线程环境中出现一些意外结果。

关于java - 通过线程池运行可运行,我应该使用 volatile 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41346886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com