当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
2种使用方法
Synchronized method()
synchronized(this){/*区块*/},它的作用域是当前对象(只对同一个对象的多线程起作用);
注意:1 Synchronized只对同一个对象的多线程起作用,同一个类不同的对象实例的synchronized方法是不相干扰的
2 Synchronized static Method{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。
考虑情况
<strong>List</strong>
ArrayList ,<span style="font-family: 宋体, Arial; 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 id="recommend-content-152144503" class="recommend-text mb-10" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 10px; padding: 0px; font-family: arial, 'courier new', courier, 宋体, monospace; "><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