Java Collections synchronizedList() 方法



描述

Java Collections synchronizedList(List<T>) 方法用於返回一個由指定列表支援的同步(執行緒安全)列表。

宣告

以下是 java.util.Collections.synchronizedList() 方法的宣告。

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

引數

list − 要“包裝”到同步列表中的列表。

返回值

  • 方法呼叫返回指定列表的同步檢視。

異常

從非同步整數列表獲取同步列表示例

以下示例演示了 Java Collection synchronizedList(List) 方法的用法。我們建立了一個包含一些整數的 List 物件。使用 synchronizedList(List) 方法,我們檢索了列表的同步版本並列印了列表。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
	  
      // synchronized version of list
      List<Integer> c = Collections.synchronizedList(list);
      System.out.println("Synchronized list: "+ c);
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Synchronized list: [1, 2, 3, 4, 5]

從非同步字串列表獲取同步列表示例

以下示例演示了 Java Collection synchronizedList(List) 方法的用法。我們建立了一個包含一些字串的 List 物件。使用 synchronizedList(List) 方法,我們檢索了列表的同步版本並列印了列表。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<String> list = new ArrayList<>(Arrays.asList("Welcome","to","Tutorialspoint"));

      // synchronized version of list
      List<String> c = Collections.synchronizedList(list);
      System.out.println("Synchronized list: "+ c);
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Synchronized list: [Welcome, to, Tutorialspoint]

從非同步物件列表獲取同步列表示例

以下示例演示了 Java Collection synchronizedList(List) 方法的用法。我們建立了一個包含一些 Student 物件的 List 物件。使用 synchronizedList(List) 方法,我們檢索了列表的同步版本並列印了列表。

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<Student> list = new ArrayList<>(Arrays.asList(new Student(1, "Julie"),
         new Student(2, "Robert"), new Student(3, "Adam")));

      // synchronized version of list
      List<Student> c = Collections.synchronizedList(list);
      System.out.println("Synchronized list: "+ c);
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Synchronized list: [[ 1, Julie ], [ 2, Robert ], [ 3, Adam ]]
java_util_collections.htm
廣告