java - 从线程调用类的方法时是否存在并发问题的可能性?
问题描述
public class ThreadTest {
private final ListeningExecutorService executor;
public ThreadTest() {
this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}
public void processAsync() {
int i=0;
do {
final Future<Integer> future = processThread(i));
futures.add(future);
i++;
} while (i<10);
int count = 0;
for (Future<Integer> f : futures) {
try {
count+=f.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Error occurred", e);
}
}
}
private Integer updateCount(Integer i) {
Integer a = Math(i,2);
a = a + 20;
Integer b = a + 40;
return b;
}
public ListenableFuture<Integer> processThread(Integer i) {
return this.executor.submit(()->{
return updateCount(i);
});
}
在这小段代码中,updateCount()
如果我调用processAsync()
类的方法,是否需要同步方法中的任何内容?多个线程调用会updateCount()
导致临时变量不created(i, a , b)
同步并返回垃圾值吗?
解决方案
推荐阅读
- micronaut - 是否可以在 Micronauts 中刷新 AWS 参数存储属性
- reactjs - 使用图像和描述反应组合框选择
- ansible - 在 YAML 中为 Ansible 循环内部变量
- flutter - 如何导航到具有构造函数参数的页面?
- reactjs - 尝试从一个对象渲染多个属性到单个 JSX 元素 - React 组件
- mongodb - 已连接到 MLab,但不会连接到 localhost
- python - 计算列表中的连续出现和
- mysql - mysqldump:无法执行 'SHOW PACKAGE STATUS WHERE Db = 当 rake db:migrate 完成迁移时
- python-3.x - Python Selenium:如何优化按钮选择和提交过程?
- java - 将多个分隔符传递给 StringTokenizer 构造函数