Java中有哪些无锁技术来解决并发问题?如何使用?( 二 )


package constxiong.concurrency.a026;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.CopyOnWriteArrayList;/** * 测试 copy-on-write * @author ConstXiong */public class TestCopyOnWrite { private static final Random R = new Random();private static CopyOnWriteArrayList<Integer> cowList = new CopyOnWriteArrayList<Integer>();// private static ArrayList<Integer> cowList = new ArrayList<Integer>();public static void main(String[] args) throws InterruptedException { List<Thread> threadList = new ArrayList<Thread>(); //启动 1000 个线程,向 cowList 添加 5 个随机整数 for (int i = 0; i <1000; i++) { Thread t = new Thread(() -> { for (int j = 0; j <5; j++) { //休眠 10 毫秒,让线程同时向 cowList 添加整数,引出并发问题 try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } cowList.add(R.nextInt(100)); } }) ; t.start(); threadList.add(t); }for (Thread t : threadList) { t.join(); } System.out.println(cowList.size()); }}打印结果
5000如果把
private static CopyOnWriteArrayList<Integer> cowList = new CopyOnWriteArrayList<Integer>();改为
private static ArrayList<Integer> cowList = new ArrayList<Integer>();打印结果就是小于 5000 的整数了

【Java中有哪些无锁技术来解决并发问题?如何使用?】


推荐阅读