当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
2种使用方法
Synchronized method()
synchronized(this){/*区块*/},它的作用域是当前对象(只对同一个对象的多线程起作用);
注意:1 Synchronized只对同一个对象的多线程起作用,同一个类不同的对象实例的synchronized方法是不相干扰的
2 Synchronized static Method{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。
线程安全的集合主要包括:ConcurrentLinkedQueue、ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentSkipListSet等,相关内容请到java.util.concurrent包中进行查询。
List
ArrayList ,LinkedList不同步 Vector同步
ArrayList 如果要同步的话 List list = Collections.synchronizedList(new ArrayList(...)); 参考api
SetHashSet,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());