Java Collections synchronizedList()

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

1 语法

public static <T> List<T> synchronizedList(List<T> list)  

2 参数

list:该列表将包装在同步列表中。

3 返回值

返回指定列表的同步列表。

4 synchronizedList示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create ArrayList object
        List<String> list = new ArrayList<String>();
        //Add values in the list
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        //Create a synchronized list
        List<String> synlist = Collections.synchronizedList(list);
        System.out.println("Synchronized list is :"+synlist);
    }
}

输出结果为:

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

5 synchronizedList示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.synchronizedList的例子
 */
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 List
        List<Integer> coll = Collections.synchronizedList(list);
        System.out.println("Synchronized list is :"+coll);
    }
}

输出结果为:

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

6 synchronizedList示例3

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) throws InterruptedException {
        List<Integer> integers = new ArrayList<>();
        List<Integer> list = Collections.synchronizedList(integers);
        Collections.addAll(list, new Integer[10000]);
        System.out.println("Initial size: " + list.size());
        final ExecutorService e = Executors.newFixedThreadPool(10);
        for (int i = 0; i < list.size(); i++) {
            e.execute(() -> list.remove(0));
        }
        e.shutdown();
        e.awaitTermination(1000, TimeUnit.SECONDS);
        System.out.println(list.size());//should be zero
    }
}

输出结果为:

Initial size: 10000
4896

 

热门文章

优秀文章