Java Collections synchronizedMap()

synchronizedMap() 用于获取由指定映射支持的同步(线程安全)映射。

1 语法

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)

2 参数

m:该Map将被包装在同步的Map中。

3 返回值

返回指定Map的同步Map。

4 synchronizedMap()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "Eric");
        map.put("4", "Jack");
        map.put("3", "Rose");
        Map<String, String> synmap = Collections.synchronizedMap(map);
        System.out.println("Synchronized map is :" + synmap);
    }
}

输出结果为:

Synchronized map is :{1=Eric, 3=Rose, 4=Jack}

5 synchronizedMap()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        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 map: " + map);
        Map<Integer, Integer> synmap = Collections.synchronizedMap(map);
        map.remove(4, 1004);
        System.out.println("Synchronized 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}

6 synchronizedMap()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedMap的例子
 */
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo {

    private static AtomicInteger counter = new AtomicInteger();
    public static void main(String[] args) throws  InterruptedException{
        Map<Integer, Integer> m = new HashMap<>();
        Map<Integer, Integer> map = Collections.synchronizedMap(m);
        final ExecutorService e = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10000; 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 10000
    }
}

输出结果为:

10000

 

热门文章

优秀文章