SafeCollectionIteration.java
资源名称:Source.rar [点击查看]
上传用户:songled
上传日期:2022-07-14
资源大小:94k
文件大小:1k
源码类别:
进程与线程
开发平台:
Java
- import java.util.*;
- public class SafeCollectionIteration extends Object {
- public static void main(String[] args) {
- // To be safe, only keep a reference to the
- // *synchronized* list so that you are sure
- // that all accesses are controlled.
- // The collection *must* be synchronized
- // (a List in this case).
- List wordList =
- Collections.synchronizedList(new ArrayList());
- wordList.add("Iterators");
- wordList.add("require");
- wordList.add("special");
- wordList.add("handling");
- // All of this must be in a synchronized block to
- // block other threads from modifying wordList while
- // the iteration is in progress.
- synchronized ( wordList ) {
- Iterator iter = wordList.iterator();
- while ( iter.hasNext() ) {
- String s = (String) iter.next();
- System.out.println("found string: " + s +
- ", length=" + s.length());
- }
- }
- }
- }