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) { // To be on the safe side, use only one reference to the sync list, this ensures that all access is controlled //The collection must be synchronized, here is a List List wordList = Collections.synchronizedList(new ArrayList()); //The add method in wordList is a synchronous method, which will acquire the object lock of the wordList instance wordList.add("Iterators"); wordList.add("require"); wordList.add("special"); wordList.add("handling"); //Get the object lock of the wordList instance, //When iterating, block other threads to call methods such as add or remove to modify elements synchronized ( wordList ) { Iterator iter = wordList.iterator(); while ( iter.hasNext() ) { String s = (String) iter.next(); System.out.println("found string: " + s + ", length=" + s.length()); } } } }
Donate to developers
Driven by interest, I write 免费
something with joy and sweat. I hope you like my work and can support it at the same time. Of course, if you have money to support a money field (support Alipay, WeChat, and the buckle group), if you have no money to support a personal field, thank you.
Personal homepage : http://knight-black-bob.iteye.com/
Thank you for your sponsorship, I will do better!