当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Java Collections synchronizedNavigableMap()用法及代码示例

Java Collections 类的 synchronizedNavigableMap() 方法用于获取由指定的可导航映射支持的同步(线程安全)可导航映射。

用法

以下是 synchronizedNavigableMap() 方法的声明:

public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)

参数

参数 描述 必需/可选
m 它是一个可导航Map,它将被包装在一个同步的可导航Map中。 Required

返回

synchronizedNavigableMap() 方法返回指定导航Map的同步视图。

异常

NA

兼容版本

Java 1.8 及以上

例子1

import java.util.*;
public class CollectionsSynchronizedNavigableMapExample1 {
    public static void main(String[] args) {
        NavigableMap<String, String> map = new TreeMap<String, String>();
        map.put("3", "Java");
        map.put("4", "JavaTpoint");
        map.put("2", "Facebook");
        map.put("1", "Google");
        Map<String, String> synmap = Collections.synchronizedNavigableMap(map);
        System.out.println("Synchronized navigable map is:" + synmap);	            
          }
}

输出:

Synchronized navigable map is:{1=Google, 2=Facebook, 3=Java, 4=JavaTpoint}

例子2

import java.util.*;
public class CollectionsSynchronizedNavigableMapExample2 {
    public static void main(String[] args) {
        NavigableMap<Integer, Integer> map = new TreeMap<>();
        map.put(1, 1001);
        map.put(2, 1002);
        map.put(3, 1003);
        map.put(4, 1004);
        map.put(5, 1005);
        System.out.println("Map before Synchronized navigable map:" + map);
        Map<Integer, Integer> synmap = Collections.synchronizedNavigableMap(map);	
         map.remove(4, 1004);
         System.out.println("Synchronized navigable map after remove(4, 1004):" + synmap);
         }
}

输出:

Map before Synchronized map:{1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
Synchronized map after remove(4, 1004):{1=1001, 2=1002, 3=1003, 5=1005}

例子3

import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CollectionsSynchronizedNavigableMapExample3 {
    private static AtomicInteger counter = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {
        NavigableMap<Integer, Integer> m = new TreeMap<>();
        NavigableMap<Integer, Integer> map = Collections.synchronizedNavigableMap(m);
        final ExecutorService e = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            e.execute(() -> map.put(counter.incrementAndGet(),
                    (int) (Math.random() * 100)));
        }
        e.shutdown();
        e.awaitTermination(1000, TimeUnit.SECONDS);
        System.out.println(map.size());//should be 10
    }
}

输出:

10






相关用法


注:本文由纯净天空筛选整理自 Java Collections synchronizedNavigableMap() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。