Java Collections synchronizedSet()方法及示例
java.util.Collections 类的 synchronizedSet() 方法是用来返回一个由指定集合支持的同步(线程安全)集合。为了保证串行访问,对支持集的所有访问都是通过返回的集来完成的,这一点非常关键。
语法
public static <T> Set<T>
synchronizedSet(Set<T> s)
参数: 该方法将集合作为参数,被 “包装 “成一个同步集合。
返回值: 该方法返回一个指定集合的同步视图。
下面是说明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<String>
Set<String> set = new HashSet<String>();
// 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<String>
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<Integer>
Set<Integer> set = new HashSet<Integer>();
// 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<Integer>
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]