我尝试同时将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一切正常。同样的问题将发生在例如整数上。