Java中的Collections synchronizedSet()方法及示例
Java.util.Collections类的 synchronizedSet() 方法用于返回由指定集合支持的同步(线程安全)集合。为了确保串行访问,所有对支持集合的访问都必须通过返回的集合进行。
语法:
public static <T> Set<T>
synchronizedSet(Set<T> s)
参数: 该方法将集合作为参数以将其“包装”在同步集合中。
返回值: 该方法返回指定集合的同步视图。
下面是一些示例说明synchronizedSet()方法的用法
示例1:
//演示synchronizedSet()方法
//以字符串值为例
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
//创建Set<String>对象
Set<String> set = new HashSet<String>();
//填充集合
set.add("1");
set.add("2");
set.add("3");
//打印集合
System.out.println("集合 : " + set);
//创建同步集合
Set<String>
synset = Collections.synchronizedSet(set);
//打印同步集合
System.out.println("同步集合是 : "
+ synset);
}
catch (IllegalArgumentException e) {
System.out.println("抛出异常 : " + e);
}
}
}
集合 : [1, 2, 3]
同步集合是 : [1, 2, 3]
示例2:
//演示synchronizedSet()方法
//以整数值为例
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
//创建Set<Integer>对象
Set<Integer> set = new HashSet<Integer>();
//填充集合
set.add(100);
set.add(200);
set.add(300);
//打印集合
System.out.println("集合 : " + set);
//创建同步集合
Set<Integer>
synset = Collections.synchronizedSet(set);
//打印同步集合
System.out.println("同步集合是 : "
+ synset);
}
catch (IllegalArgumentException e) {
System.out.println("抛出异常 : " + e);
}
}
}
集合 : [100, 200, 300]
同步集合是 : [100, 200, 300]