import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList;
public class ConcurrentList { //private static List TEST_LIST = new CopyOnWriteArrayList (); private static List TEST_LIST = Collections.synchronizedList(new ArrayList ());
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (TEST_LIST) {
TEST_LIST.add("11");
}
System.out.println("Thread1 running");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (TEST_LIST) {
for (String at : TEST_LIST) {
TEST_LIST.add("22");
}
}
System.out.println("Thread2 running");
}
}
}).start();
}
}
List list = Collections.synchronizedList(new ArrayList());
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。