Java Collections synchronizedCollection()方法及实例

Java Collections synchronizedCollection()方法及实例

java.util.Collections 类的 synchronizedCollection() 方法是用来返回一个由指定集合支持的同步(线程安全)的集合。为了保证串行访问,对支持集合的所有访问都是通过返回的集合完成的,这一点至关重要。

语法:

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

参数: 该方法以 集合c 为参数,被 “包装 “成一个同步集合。

返回值: 该方法返回指定集合的 同步视图

下面是说明synchronizedCollection()方法的例子

例1:

// Java program to demonstrate synchronizedCollection()
// method for String Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // creating object of List<String>
            List<String> vector = new ArrayList<String>();
 
            // populate the vector
            vector.add("A");
            vector.add("B");
            vector.add("C");
            vector.add("D");
            vector.add("E");
 
            // printing the Collection
            System.out.println("Collection : " + vector);
 
            // getting the synchronized view of Collection
            Collection<String> c = Collections
                                       .synchronizedCollection(vector);
 
            // printing the Collection
            System.out.println("Synchronized view"
                               + " of collection : " + c);
        }
 
        catch (IndexOutOfBoundsException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出

Collection : [A, B, C, D, E]
Synchronized view of collection : [A, B, C, D, E]

例2:

// Java program to demonstrate synchronizedCollection()
// method for Integer Value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
 
        try {
 
            // creating object of List<String>
            List<Integer> vector = new ArrayList<Integer>();
 
            // populate the vector
            vector.add(20);
            vector.add(30);
            vector.add(40);
            vector.add(50);
            vector.add(60);
 
            // printing the Collection
            System.out.println("Collection : " + vector);
 
            // getting the synchronized view of Collection
            Collection<Integer> c = Collections
                                        .synchronizedCollection(vector);
 
            // printing the Collection
            System.out.println("Synchronized view is : " + c);
        }
 
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出

Collection : [20, 30, 40, 50, 60]
Synchronized view is : [20, 30, 40, 50, 60]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程