问题
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
BaseCallable callable = new BaseCallable();
callable.name = "A";
Future<String> future1 = executorService.submit(callable);
callable.name = "B";
Future<String> future2 = executorService.submit(callable);
System.out.println(future1.get());
System.out.println(future2.get());
}
}
class BaseCallable implements Callable<String> {
public String name;
@Override
public String call() throws Exception {
return name;
}
}
结果
原因
其结果都为B,由于主线程会比子线程快速执行完,所以两次任务都用到的是同一个变量。