炫意html5
最早CSS3和HTML5移动技术网站之一

java多线程-主线程等待多个子线程处理结果,子线程结果不完整

public class ThreadTest {

public static void main(String[] args) {
System.out.println("main begin");
CountDownLatch cunt = new CountDownLatch(5);
List<String> out = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i=0;i<5;i++){
executorService.execute(new TaskTest(i+"",cunt,out));
}
try {
cunt.await();
}catch (Exception e){
}
executorService.shutdown();
System.out.println(out);
System.out.println("main out");
}

}
@Data
@NoArgsConstructor
@AllArgsConstructor
class TaskTest implements Runnable{

private String name;
private CountDownLatch countDownLatch;
private List<String> result;
@Override
public void run() {
countDownLatch.countDown();
result.add("11");
System.out.println("thread:"+name);
}

}

主线程中打印的out理论上应该是:[11, 11, 11, 11, 11],但是会出现[null, 11, 11, 11, 11]或者[null, null, 11, 11, 11],是什么原因?

回答

new CountDownLatch(5);
改为
new CountDownLatch(6);

主线程也执行 countDown();
cunt.countDown();

试试。

炫意HTML5 » java多线程-主线程等待多个子线程处理结果,子线程结果不完整

Java基础教程Android基础教程