您的位置:首页 > 其它

Synchronized同步的考虑

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

2种使用方法

Synchronized method()

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

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

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

考虑情况

在多线程程序中,应当尽量使用线程安全的集合。在集合的修改和查询过程中往往涉及到很多复杂的操作。比如set集合,在添加或删除元素时,需要对其中的树结构进行调整,一般需要在log(n)时间内才能完成,这样如果两个线程同时对同一个集合进行修改,就很可能造成这个集合的崩溃。可以使用读写锁来对集合的修改加以控制,但是这种控制往往是复杂的,并且低效。因此java提供了一些线程安全的集合类,在多线程程序中可以使用这些线程安全的集合以避免可能的不一致和崩溃现象。

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

<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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: