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

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

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

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

句法:

public static  SortedSet
  synchronizedSortedSet(SortedSet s)

参数:此方法将排序集作为参数“包装”在同步排序集中。

返回值:此方法返回指定排序集的同步视图

以下是说明 synchronizedSortedSet() 方法的示例

示例 1:

// Java program to demonstrate
// synchronizedSortedSet() method
// for  Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of SortedSet
            SortedSet set = new TreeSet();
  
            // populate the set
            set.add("A");
            set.add("B");
            set.add("C");
            set.add("D");
  
            // printing the Collection
            System.out.println("Sorted Set : " + set);
  
            // create a synchronized sorted set
            SortedSet
                sorset = Collections
                             .synchronizedSortedSet(set);
  
            // printing the set
            System.out.println("Sorted set is : "
                               + sorset);
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
Sorted Set : [A, B, C, D]
Sorted set is : [A, B, C, D]

示例 2:

// Java program to demonstrate
// synchronizedSortedSet() method
// for  Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of SortedSet
            SortedSet
                set = new TreeSet();
  
            // populate the set
            set.add(10);
            set.add(20);
            set.add(30);
            set.add(40);
  
            // printing the Collection
            System.out.println("Sorted Set : " + set);
  
            // create a synchronized sorted set
            SortedSet
                sorset = Collections
                             .synchronizedSortedSet(set);
  
            // printing the set
            System.out.println("Sorted set is : "
                               + sorset);
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
Sorted Set : [10, 20, 30, 40]
Sorted set is : [10, 20, 30, 40]