java.util.Collections类的synchronizedCollection()方法用于返回指定集合支持的同步(线程安全)集合。为了保证串行访问,至关重要的是所有对后备集合的访问都必须通过返回的集合来完成。
用法:
public static Collection
synchronizedCollection(Collection c)
参数:此方法将集合c作为参数,作为同步集合中的“wrapped”。
返回值:此方法返回指定集合的同步视图。
以下示例说明了synchronizedCollection()方法
示例1:
// Java program to demonstrate synchronizedCollection()
// method for String Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of List
List vector = new ArrayList();
// populate the vector
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
// printing the Collection
System.out.println("Collection : " + vector);
// getting the syncronised view of Collection
Collection c = Collections
.synchronizedCollection(vector);
// printing the Collection
System.out.println("Synchronized view"
+ " of collecttion : " + c);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Collection : [A, B, C, D, E]
Synchronized view of collecttion : [A, B, C, D, E]
示例2:
// Java program to demonstrate synchronizedCollection()
// method for Integer Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of List
List vector = new ArrayList();
// populate the vector
vector.add(20);
vector.add(30);
vector.add(40);
vector.add(50);
vector.add(60);
// printing the Collection
System.out.println("Collection : " + vector);
// getting the syncronised view of Collection
Collection c = Collections
.synchronizedCollection(vector);
// printing the Collection
System.out.println("Synchronized view is : " + c);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Collection : [20, 30, 40, 50, 60]
Synchronized view is : [20, 30, 40, 50, 60]