java.util.Collections類的synchronizedList()方法用於返回由指定列表支持的同步(線程安全)列表。為了保證串行訪問,至關重要的是,對後備列表的所有訪問都必須通過返回的列表來完成。
用法:
public static <T> List<T> synchronizedList(List<T> list)
參數:此方法將列表作為參數,作為同步列表中的“wrapped”。
返回值:此方法返回指定列表的同步視圖。
以下示例說明了synchronizedList()方法
示例1:
// Java program to demonstrate
// synchronizedList() 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> list = new ArrayList<String>();
// populate the list
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
// printing the Collection
System.out.println("List : " + list);
// create a synchronized list
List<String> synlist = Collections
.synchronizedList(list);
// printing the Collection
System.out.println("Synchronized list is : " + synlist);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
輸出:
List : [A, B, C, D, E] Synchronized list is : [A, B, C, D, E]
示例2:
// Java program to demonstrate
// synchronizedList() method for Integer Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of List<Integer>
List<Integer> list = new ArrayList<Integer>();
// populate the list
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(60);
// printing the Collection
System.out.println("List : " + list);
// create a synchronized list
List<Integer> synlist = Collections
.synchronizedList(list);
// printing the Collection
System.out.println("Synchronized list is : " + synlist);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
輸出:
List : [20, 30, 40, 50, 60] Synchronized list is : [20, 30, 40, 50, 60]
相關用法
- Java Collections max()用法及代碼示例
- Java Collections min()用法及代碼示例
- Java Collections asLifoQueue()用法及代碼示例
- Java Collections synchronizedCollection()用法及代碼示例
- Java Collections swap()用法及代碼示例
- Java Collections unmodifiableCollection()用法及代碼示例
- Java Collections list()用法及代碼示例
- Java Collections newSetFromMap()用法及代碼示例
- Java Collections replaceAll()用法及代碼示例
- Java Collections singletonMap()用法及代碼示例
- Java Collections singletonList()用法及代碼示例
- Java Collections checkedSet()用法及代碼示例
- Java Collections synchronizedMap()用法及代碼示例
- Java Collections synchronizedSet()用法及代碼示例
- Java Collections synchronizedSortedMap()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections synchronizedList() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。