为什么每个线程都不会在CopyOnWriteArrayList中同时添加对象?

时间:2018-12-29 10:19:12

标签: executorservice copyonwritearraylist

我尝试同时将myObject添加到CopyOnWriteArrayList,但执行后列表对象为空。

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class NMain {
    private static CopyOnWriteArrayList<MyClass> list;

    public static void main(String[] args) {
        final ExecutorService EXECUTOR_SERVICE = Executors.  newFixedThreadPool(Runtime.getRuntime() .availableProcessors());
        try {
            submit(EXECUTOR_SERVICE);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        EXECUTOR_SERVICE.shutdown();
        try {
            EXECUTOR_SERVICE.awaitTermination(10 * 2000,   TimeUnit.MILLISECONDS);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    private static void submit(ExecutorService exe) throws InterruptedException  {
        for(int i=0; i<50; i++) {
            exe.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        MyClass myObject = new MyClass();
                        list.add(myObject);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

MyClass一切正常。同样的问题将发生在例如整数上。

0 个答案:

没有答案