Java Collections synchronizedSortedMap()方法及示例

Java Collections synchronizedSortedMap()方法及示例

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

语法

public static <K, V> SortedMapK, V>
  synchronizedSortedMap(SortedMapK, V> m)

参数: 该方法将排序后的Map作为参数,被 “包裹 “在一个同步排序的Map中。

返回值: 该方法返回指定排序Map的同步视图。

下面是说明 synchronizedSortedMap() 方法的例子

例1 :

// Java program to demonstrate
// synchronizedSortedMap() method
// for <String, String> Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of SortedMap<String, String>
            SortedMap<String, String>
                map = new TreeMap<String, String>();
  
            // populate the map
            map.put("1", "A");
            map.put("2", "B");
            map.put("3", "C");
  
            // printing the Collection
            System.out.println("Sorted Map : " + map);
  
            // create a sorted map
            SortedMap<String, String>
                sortedmap = Collections
                                .synchronizedSortedMap(map);
  
            // printing the map
            System.out.println("Synchronized sorted map is :"
                               + sortedmap);
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出。

Sorted Map : {1=A, 2=B, 3=C}
Synchronized sorted map is :{1=A, 2=B, 3=C}

例2 :

// Java program to demonstrate
// synchronizedSortedMap() method
// for <Integer, Boolean> Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of SortedMap<Integer, Boolean>
            SortedMap<Integer, Boolean>
                map = new TreeMap<Integer, Boolean>();
  
            // populate the map
            map.put(100, true);
            map.put(200, true);
            map.put(300, true);
  
            // printing the Collection
            System.out.println("Sorted Map : " + map);
  
            // create a sorted map
            SortedMap<Integer, Boolean>
                sortedmap = Collections
                                .synchronizedSortedMap(map);
  
            // printing the map
            System.out.println("Synchronized sorted map is :"
                               + sortedmap);
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出。

Sorted Map : {100=true, 200=true, 300=true}
Synchronized sorted map is :{100=true, 200=true, 300=true}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程