2种使用方法
Synchronized method()
synchronized(this){/*区块*/},它的作用域是当前对象(只对同一个对象的多线程起作用);
注意:1 Synchronized只对同一个对象的多线程起作用,同一个类不同的对象实例的synchronized方法是不相干扰的
2 Synchronized static Method{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。
考虑情况
<strong>List</strong>
ArrayList ,<span style="font-family:宋体,Arial; font-size:14px; line-height:21px; background-color:rgb(255,252,243)">LinkedList</span>不同步 Vector同步
ArrayList 如果要同步的话 List list = Collections.synchronizedList(new ArrayList(...)); 参考api
<span style="font-family:宋体; font-size:16px; line-height:24px"></span><pre class="recommend-text mb-10" id="recommend-content-152144503" style="margin-top:0px; margin-bottom:10px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:arial,'courier new',courier,宋体,monospace; white-space:pre-wrap; word-wrap:break-word" name="code"><strong>Set</strong>HashSet,LinkedHashSet不同步
<strong>Map</strong>
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());
参考api
转自http://blog.csdn.net/sd0902/article/details/8292601