public class SynchronizedCollectionExample {
private List<Integer> list = new ArrayList<>();
public void add(int value) {
synchronized (SynchronizedCollectionExample.class) {
list.add(value);
}
}
public int get(int index) {
synchronized (SynchronizedCollectionExample.class) {
return list.get(index);
}
}
}
public class ThreadLocalCollectionExample {
private ThreadLocal<List<Integer>> threadLocalList = ThreadLocal.withInitial(ArrayList::new);
public void add(int value) {
threadLocalList.get().add(value);
}
public int get(int index) {
return threadLocalList.get().get(index);
}
}
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class CollectionsSynchronizedExample {
List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<Integer>());
public void add(int value) {
synchronizedList.add(value);
}
public int get(int index) {
return synchronizedList.get(index);
}
}
import com.google.common.collect.ImmutableList;
public class ImmutableCollectionExample {
private ImmutableList<Integer> immutableList = ImmutableList.of(1, 2, 3);
public int get(int index) {
return immutableList.get(index);
}
}
或者:
import java.util.List;
public class ImmutableJava9Example {
private List<Integer> immutableList = List.of(1, 2, 3);
public int get(int index) {
return immutableList.get(index);
}
}
Java1.5并发包(java.util.concurrent)包含线程安全集合类,允许在迭代时修改集合。
Java并发集合类主要包含以下几种: