import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
//public static Collection synchronizedCollention(Collection c)
//
//public static List synchronizedList(list l)
//
//public static Map synchronizedMap(Map m)
//
//public static Set synchronizedSet(Set s)
//
//public static SortedMap synchronizedSortedMap(SortedMap sm)
//
//public static SortedSet synchronizedSortedSet(SortedSet ss)
public class CollectionsSynchronizedTest {
public static void main(String[] args) {
//為了安全起見,僅使用同步清單的一個引用,這樣可以確定控制了所有通路
//集合必須同步化,這裡是一個List
List wordList = Collections.synchronizedList(new ArrayList());
//wordList中的add方法是同步方法,會擷取wordList執行個體的對象鎖
wordList.add("Iterators");
wordList.add("require");
wordList.add("special");
wordList.add("handling");
//擷取wordList執行個體的對象鎖,
//疊代時,阻塞其他線程調用add或remove等方法修改元素
synchronized ( wordList ) {
Iterator iter = wordList.iterator();
while ( iter.hasNext() ) {
String s = (String) iter.next();
System.out.println("found string: " + s + ", length=" + s.length());
}
}
}
}
捐助開發者
在興趣的驅動下,寫一個
免費
的東西,有欣喜,也還有汗水,希望你喜歡我的作品,同時也能支援一下。 當然,有錢捧個錢場(支援支付寶和微信 以及扣扣群),沒錢捧個人場,謝謝各位。
個人首頁:
http://knight-black-bob.iteye.com/
謝謝您的贊助,我會做的更好!