首页 > 解决方案 > 从线程调用类的方法时是否存在并发问题的可能性?

问题描述

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)同步并返回垃圾值吗?

标签: javamultithreadingsynchronization

解决方案


推荐阅读