Java教程

Java Collections syncList()

Java集合类的 synchronizedList()方法用于获取支持的同步(线程安全)集合

语法

以下是 synchronizedList()方法的声明:
public static <T> List<T> synchronizedList(List<T> list)

参数

参数 说明 必需/可选
list 它是将被包装在同步列表中的列表。 必需

返回

synchronizedList()方法返回指定列表的同步视图。

异常

NA

兼容版本

Java 1.5及更高版本

示例1

import java.util.*;
public class CollectionsSynchronizedListExample1 {
    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]

示例2

import java.util.*;
public class CollectionsSynchronizedListExample2 {
    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 view is :[44, 55, 99, 77, 88, 66]

示例3

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CollectionsSynchronizedListExample3 {
    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
4573

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4