Java/자바 기본 문법
[자바] 컬렉션 인스턴스 동기화
가자미
2021. 3. 2. 15:27
public static <T> Set<T> synchronizedSet(Set<T> s)
public static <T> List<T> synchronizedList(List<T> list)
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
public static <T> Collection<T> synchronizedCollection(Collection<T> c)
//콜렉션 인스턴스를 동기화
컬렉션 인스턴스 동기화의 예
class SyncArrayList{
public static List<Integer> lst =
Collection.synchronizedList(new ArrayList<Integer>());
public static void main(String[] args) throws InterruptedException{
for(int i = 0; i<16;i++)
lst.add(i);
System.out.println(lst);
Runnable Task = ()->{
synchronized(lst) {//동기화 되지 않은 반복자 인스턴스를 활용해
//쓰레드를 활용하려면 동기화 되지 않음!!!
ListIterator<Integer> itr = lst.listIterator();
while(itr.hasNext())
itr.set(itr.next()+1);
}
};
ExecutorService exr = Executors.newFixedThreadPool(3);
exr.shutdown();
exr.awaitTermination(100,TimeUnit.SECONDS); //작업다 끝날때까지 100초 대기
}
}