---
title: "Java的容器的线程安全"
author: "speed847"
date: "2013-07-05T08:11:03Z"
tags: []
categories: ["Web前端"]
slug: "java"
draft: false
lastmod: "2013-07-05T08:11:03Z"
id: 1899877
url: "https://speed847.iteye.com/blog/1899877"
---

[http://blog.sina.com.cn/s/blog\_5efa3473010129pw.html](http://blog.sina.com.cn/s/blog_5efa3473010129pw.html)

 

 

线程安全：多个线程操作容器的时候，互相之间不会带来意想不到的影响；

 

 

 

有些容器是线程安全的（Vector,ConcurrentLinkedQueue等），有些则不是（list等），利用类似 private static List&lt;Task&gt; taskQueue = Collections.synchronizedList(new LinkedList&lt;Task&gt;());的方法可以得到本身不是线程安全的容易的线程安全的状态，但是要注意的是线程安全仅仅指的是如果直接使用它提供的函数，比如：queue.add(obj); 或者 queue.poll(obj);，这样我们自己不需要做任何同步。  
但如果是非原子操作，比如：  
   1. if(!queue.isEmpty()) {    
   2.    queue.poll(obj);    
   3. }    
我们很难保证，在调用了isEmpty()之后，poll()之前，这个queue没有被其他线程修改。  
所以对于这种情况，我们还是需要自己同步：  
   1. synchronized(queue) {    
   2.     if(!queue.isEmpty()) {    
   3.        queue.poll(obj);    
   4.     }    
   5. }    
对于Collections.synchronizedList(new LinkedList&lt;Task&gt;())，

 

在返回的列表上进行迭代时，用户必须手工在返回的列表上进行同步：

```
 List list = Collections.synchronizedList(new ArrayList()); ... synchronized(list) { Iterator i = list.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); }
```

 

不遵从此建议将导致无法确定的行为