集合的同步问题

当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。

2种使用方法   

            Synchronized method()

              synchronized(this){/*区块*/},它的作用域是当前对象(只对同一个对象的多线程起作用);


注意:1  Synchronized只对同一个对象的多线程起作用,同一个类不同的对象实例的synchronized方法是不相干扰的

        2 Synchronized static Method{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。


 线程安全的集合主要包括:ConcurrentLinkedQueueConcurrentHashMapConcurrentSkipListMapConcurrentSkipListSet等,相关内容请到java.util.concurrent包中进行查询。

List
ArrayList ,LinkedList不同步   Vector同步
ArrayList 如果要同步的话 List list = Collections.synchronizedList(new ArrayList(...));  参考api
Set
HashSet,LinkedHashSet不同步
 
Map
HashMap 不同步   HashTable 同步
<strong>Quque</strong>
LinkedBlockingQueue 同步
如果要同步非同步的集合 
 Collection c=Collections.synchronizedCollection(new ArrayList());
 List list=Collections.synchronizedList(new ArrayList());
 Set s=Collections.synchronizedSet(new HashSet());

 Map m=Collections.synchronizedMap(new HashMap());     


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值