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();
试试。
这个不行的
@二毛605332:
多线程操作,涉及到 并发问题
List<String> out = new ArrayList<>();
不是 支持并发的。
@二毛605332: 改为下面的:
List<String> out = Collections.synchronizedList(new ArrayList<>());
或者使用 Current开头的 List
ArrayList的add不是線程安全的
加鎖解決
synchronized (TaskTest.class) {
result.add(name);
}
需要阻塞主线程
executorService.awaitTermination 执行这个