【Java 同步类容器】

ArrayList线程不安全

package com.yuzhenc.collection;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: yuzhenc
 * @date: 2022-03-20 09:52:52
 * @desc: com.yuzhenc.collection
 * @version: 1.0
 */
public class Test20 {
    public static void main(String[] args) {
        //创建一个ArrayList集合
        ArrayList<String> arrayList = new ArrayList<>();
        //创建一个线程池,定长为100
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        //并发向集合中添加10000个元素
        for (int i = 0; i < 10000; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    arrayList.add("aaa");
                }
            });
        }
        //关闭线程池
        executorService.shutdown();

        //监控线程
        while(true) {
            //线程都执行完以后返回true
            if(executorService.isTerminated()) {
                System.out.println("所有子线程都执行完毕!");
                if (arrayList.size() == 10000) {
                    System.out.println("线程安全!");
                } else {
                    System.out.println(arrayList.size());
                    System.out.println("线程不安全!");
                }
                //线程执行完后,监控可以停止
                break;
            }
        }
    }
}

【Java 同步类容器】_第1张图片

同步类容器线程安全

package com.yuzhenc.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: yuzhenc
 * @date: 2022-03-20 10:17:24
 * @desc: com.yuzhenc.collection
 * @version: 1.0
 */
public class Test21 {
    public static void main(String[] args) {
        //创建一个ArrayList集合
        ArrayList<String> arrayList = new ArrayList<>();
        List<String> list = Collections.synchronizedList(arrayList);

        //创建一个线程池,定长为100
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        //并发向集合中添加10000个元素
        for (int i = 0; i < 10000; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    list.add("aaa");
                }
            });
        }
        //关闭线程池
        executorService.shutdown();

        //监控线程
        while(true) {
            //线程都执行完以后返回true
            if(executorService.isTerminated()) {
                System.out.println("所有子线程都执行完毕!");
                if (list.size() == 10000) {
                    System.out.println("线程安全!");
                } else {
                    System.out.println(list.size());
                    System.out.println("线程不安全");
                }
                //线程执行完后,监控可以停止
                break;
            }
        }
    }
}

【Java 同步类容器】_第2张图片

你可能感兴趣的:(笔记,JAVA,java)