concurrentarraylist_java-并发线程同时添加到ArrayList-会发生什么?

我想出了以下代码来模拟实际情况。

并行运行100个任务,它们将完成的状态更新到主程序。 我使用CountDownLatch等待任务完成。

import java.util.concurrent.*;

import java.util.*;

public class Runner {

// Should be replaced with Collections.synchronizedList(new ArrayList())

public List completed = new ArrayList();

/**

* @param args

*/

public static void main(String[] args) {

Runner r = new Runner();

ExecutorService exe = Executors.newFixedThreadPool(30);

int tasks = 100;

CountDownLatch latch = new CountDownLatch(tasks);

for (int i = 0; i < tasks; i++) {

exe.submit(r.new Task(i, latch));

}

try {

latch.await();

System.out.println("Summary:");

System.out.println("Number of tasks completed: "

+ r.completed.size());

} catch (InterruptedException e) {

e.printStackTrace();

}

exe.shutdown();

}

class Task implements Runnable {

private int id;

private CountDownLatch latch;

public Task(int id, CountDownLatch latch) {

this.id = id;

this.latch = latch;

}

public void run() {

Random r = new Random();

try {

Thread.sleep(r.nextInt(5000)); //Actual work of the task

} catch (InterruptedException e) {

e.printStackTrace();

}

completed.add(id);

latch.countDown();

}

}

}

当我运行该应用程序10次且至少运行3至4次时,该程序未打印正确数量的已完成任务。 理想情况下,它应该打印100(如果没有例外发生)。 但在某些情况下,它正在打印98、99等。

因此证明ArrayList的并发更新不会给出正确的结果。

如果我将ArrayList替换为Synchronized版本,则程序将输出正确的结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值