方式一:Vector public class ThreadDemo05 { public static void main(String[] args) { //方案一:解决list线程不安全的原因(因为在底层添加了sync的锁) Vectorlist=new Vector<>(); // List list = new ArrayList<>(); for (int i = 1; i <= 30; i++) { new Thread(() -> { list.add(UUID.randomUUID().toString().substring(0, 8)); System.out.println(list); }, String.valueOf(i)).start(); } } }
方式二:Collections
public class ThreadDemo06 { public static void main(String[] args) { //方案二:解决list线程不安全的原因(因为在添加了sync的锁) // Listlist = new ArrayList<>(); List list= Collections.synchronizedList(new ArrayList<>()); for (int i = 1; i <= 30; i++) { new Thread(() -> { list.add(UUID.randomUUID().toString().substring(0, 8)); System.out.println(list); }, String.valueOf(i)).start(); } } }
方式一和方式二比较古老
public class ThreadDemo07 { public static void main(String[] args) { //方案三:写时复制技术(并发读) // Listlist = new ArrayList<>(); List list= new CopyOnWriteArrayList<>(); for (int i = 1; i <= 30; i++) { new Thread(() -> { list.add(UUID.randomUUID().toString().substring(0, 8)); System.out.println(list); }, String.valueOf(i)).start(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)