📜  Java中的集合 synchronizedSet() 方法及示例

📅  最后修改于: 2022-05-13 01:55:17.965000             🧑  作者: Mango

Java中的集合 synchronizedSet() 方法及示例

Java.util.Collections类的synchronizedSet()方法用于返回由指定集合支持的同步(线程安全)集合。为了保证串行访问,对支持集的所有访问都是通过返回集完成的,这一点至关重要。

句法:

public static  Set
  synchronizedSet(Set 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
            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]