前言:最近遇到一个关于线程使用的问题,刚开始看代码并没有发现任何问题,通过for循环创建Callable,并装入List中,然后再利用executorService的invokeAll一次性执行,利用这种方式来进行Excel报表导出。但是多番测试下才发现,无论测试多少次,所以Callable运行的内容,总是和最后一个Callable的内容一致。现在问题已解决,所以又来记录一下。
先贴出模拟的问题代码:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Test test=new Test();
ExecutorService executorService = Executors.newSingleThreadExecutor();
List<Callable<List<String>>> list=new ArrayList<>();
A a=new A();
//总页数
int totalPage=10;
Future<?> taskPool = executorService.submit(() -> {
int testIndex=0;
for(int i=0;i<totalPage;i++)
{
testIndex = i+1;
a.setB(testIndex);
System.out.println("1:"+a.getB());
Callable<List<String>> c=new Callable<List<String>>() {
public List<String> call() throws Exception {
System.out.println("2:"+a.getB());
return test.getString(a);
}
};
list.add(c);
}});
System.out.println("taskPool.get:"+taskPool.get());
List<Future<List<String>>> lf=executorService.invokeAll(list);
if(lf.size()>0) {
lf.forEach(l->{
try {
synchronized(l.get()){
System.out.println("3:"+l.get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
}
public List<String> getString(A str){
List<String> strList=new ArrayList<>();
strList.add(String.valueOf(str.getB()));
return strList;
}
}
运行结果如下:
1:1
1:2
1:3
1:4
1:5
1:6
1:7
1:8
1:9
1:10
taskPool.get:null
2:10
2:10
2:10
2:10
2:10
2:10
2:10
2:10
2:10
2:10
3:[10]
3:[10]
3:[10]
3:[10]
3:[10]
3:[10]
3:[10]
3:[10]
3:[10]
3:[10]
从输出来看,问题不是出现在循环中的参数,而是出现在Callable,所以经过思考,我认为很大可能是Callable下的引用对象引发的问题,然后经过测试,肯定问题就是出在对象“a”上。
我个人认为,每一个Callable都是引用同一个对象“a”,虽然每次都在循环中更改了“a”的属性,但他们其实都共用了同一个对象,所以才会导致运行时,所有Callable中的“a”都是最后一次循环中的“a”,值都是10.
因此我尝试在每次循环都创建一个新的对象,测试后确实正常了。所以总结问题的原因应该就是这个了。
更改内容:
Future<?> taskPool = executorService.submit(() -> {
int testIndex=0;
for(int i=0;i<10;i++)
{
testIndex = i+1;
A a1=new A();
a1.setB(testIndex);
System.out.println("1:"+a1.getB());
Callable<List<String>> c=new Callable<List<String>>() {
public List<String> call() throws Exception {
System.out.println("2:"+a1.getB());
return test.getString(a1);
}
};
list.add(c);
}});
运行结果:
1:1
1:2
1:3
1:4
1:5
1:6
1:7
1:8
1:9
1:10
taskPool.get:null
2:1
2:2
2:3
2:4
2:5
2:6
2:7
2:8
2:9
2:10
3:[1]
3:[2]
3:[3]
3:[4]
3:[5]
3:[6]
3:[7]
3:[8]
3:[9]
3:[10]