safecollectioniteration.java

来自「Java Thread Programming (Source」· Java 代码 · 共 32 行

JAVA
32
字号
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());
			}
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?