java 同步list_Java Collections synchronizedList()用法及代码示例

java.util.Collections类的synchronizedList()方法用于返回由指定列表支持的同步(线程安全)列表。为了保证串行访问,至关重要的是,对后备列表的所有访问都必须通过返回的列表来完成。

用法:

public static List

synchronizedList(List 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

List list = new ArrayList();

// 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 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

List list = new ArrayList();

// 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 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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值