Java Collections synchronizedCollection()

syncedCollection() 用于获取由指定集合支持的同步(线程安全)集合。

1 语法

public static <T> Collection<T> synchronizedCollection(Collection<T> c)  

2 参数

c:它是要“包装”在同步集合中的集合。

3 返回值

返回指定集合的同步集合。

4 synchronizedCollection()示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create vector object
        Vector<String> vector = new Vector<String>();
        //Add values in the vector
        vector.add("A");
        vector.add("B");
        vector.add("C");
        vector.add("D");
        vector.add("E");
        //Create a synchronized view
        Collection<String> coll = Collections.synchronizedCollection(vector);
        System.out.println("Synchronized view is :"+coll);
    }
}

输出结果为:

Synchronized view is :[A, B, C, D, E]

5 synchronizedCollection()示例2

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create a list with items
        List<Integer> list = Arrays.asList(44, 55, 99, 77, 88, 66);
        //Create a synchronized view
        Collection<Integer> coll = Collections.synchronizedCollection(list);
        System.out.println("Synchronized view is :"+coll);
    }
}

输出结果为:

Synchronized view is :[44, 55, 99, 77, 88, 66]

6 synchronizedCollection()示例3

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        Collection<String> obj = new ArrayList<>();
        obj.add("Yiidian"); // not thread safe
        Collection<String> synObj = Collections.synchronizedCollection(obj);
        synObj.add("SM1234"); // thread safe
        //Below iteration will result in non-deterministic behavior
        Iterator<String> ite1 = synObj.iterator();
        while (ite1.hasNext()) {
            String s = ite1.next();
            System.out.println(s);
        }
        //Below code is the right way to iterate synchronized collection
        synchronized(synObj) {
            Iterator<String> ite2 = synObj.iterator();
            while (ite2.hasNext()) {
                String s = ite2.next();
                System.out.println(s);
            }
        }
    }
}

输出结果为:

Yiidian
SM1234
Yiidian
SM1234

 

热门文章

优秀文章