java.util.Collections类的synchronizedSet()方法用于返回由指定集合支持的同步(线程安全)集合。为了保证串行访问,至关重要的是,对后备集的所有访问都必须通过返回的集来完成。
用法:
public static Set
synchronizedSet(Set s)
参数:此方法将集合作为同步集合中的“wrapped”作为参数。
返回值:此方法返回指定集合的同步视图。
以下示例说明了synchronizedSet()方法
示例1:
// Java program to demonstrate
// synchronizedSet() method
// for String Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of Set
Set set = new HashSet();
// populate the set
set.add("1");
set.add("2");
set.add("3");
// printing the Collection
System.out.println("Set : " + set);
// create a synchronized set
Set
synset = Collections.synchronizedSet(set);
// printing the set
System.out.println("Synchronized set is : "
+ synset);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Set : [1, 2, 3]
Synchronized set is : [1, 2, 3]
示例2:
// Java program to demonstrate
// synchronizedSet() method
// for Integer Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of Set
Set set = new HashSet();
// populate the set
set.add(100);
set.add(200);
set.add(300);
// printing the Collection
System.out.println("Set : " + set);
// create a synchronized set
Set
synset = Collections.synchronizedSet(set);
// printing the set
System.out.println("Synchronized set is : "
+ synset);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Set : [100, 200, 300]
Synchronized set is : [100, 200, 300]