一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java集合框架线程同步代码详解

时间:2017-12-27 编辑:猪哥 来源:一聚教程网

List接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括null在内的所有元素。除了实现List接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。(此类大致上等同于Vector类,除了此类是不同步的。)size、isEmpty、get、set、iterator和listIterator操作都以固定时间运行。add操作以分摊的固定时间运行,也就是说,添加n个元素需要O(n)时间。其他所有操作都以线性时间运行(大体上讲)。与用于LinkedList实现的常数因子相比,此实现的常数因子较低。每个ArrayList实例都有一个容量。该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向ArrayList中不断添加元素,其容量也自动增长。并未指定增长策略的细节,因为这不只是添加元素会带来分摊固定时间开销那样简单。在添加大量元素前,应用程序可以使用ensureCapacity操作来增加ArrayList实例的容量。这可以减少递增式再分配的数量。

注意,此实现不是同步的。

如果多个线程同时访问一个ArrayList实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)这一般通过对自然封装该列表的对象进行同步操作来完成。如果不存在这样的对象,则应该使用Collections.synchronizedList方法将该列表“包装”起来。这最好在创建时完成,以防止意外对列表进行不同步的访问:

Listlist=Collections.synchronizedList(newArrayList(...));

此类的iterator和listIterator方法返回的迭代器是快速失败的:在创建迭代器之后,除非通过迭代器自身的remove或add方法从结构上对列表进行修改,否则在任何时间以任何方式对列表进行修改,迭代器都会抛出ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。

注意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证。快速失败迭代器会尽最大努力抛出ConcurrentModificationException。因此,为提高这类迭代器的正确性而编写一个依赖于此异常的程序是错误的做法:迭代器的快速失败行为应该仅用于检测bug。

如上所示,现在建立一个list集合,一个线程对集合进行写入操作,一个线程进行删除操作

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class MyArrayList {
	/** 
   * 创建一个列表,一个线程进行写入,一个线程读取 iterator 和 listIterator 方法返回的迭代器是快速失败的 
   */
	public void readWrite() {
		List nums = new ArrayList();
		List synNums = Collections.synchronizedList(nums);
		//启动写入线程 
		new WriteListThread(synNums).start();
		//启动删除线程 
		new DeleteListThread(synNums).start();
	}
	public static void main(String[] args) {
		new MyArrayList().readWrite();
	}
}
class WriteListThread extends Thread {
	private List nums;
	public WriteListThread(List nums) {
		super(“WriteListThread”);
		this.nums = nums;
	}
	// 不停写入元素1 
	public void run() {
		while (true) {
			nums.add(new Random().nextint(1000));
			System.out.println(Thread.currentThread().getName());
		}
	}
}
class DeleteListThread extends Thread {
	private List nums;
	public DeleteListThread(List nums) {
		super(“DeleteListThread”);
		this.nums = nums;
	}
	// 删除第一个元素 
	public void run() {
		while (true) {
			try{
				System.out.println(Thread.currentThread().getName()+”:”+nums.remove(0));
			}
			catch(Exception e){
				continue ;
			}
		}
	}
}

通过ListsynNums=Collections.synchronizedList(nums);就能对原子操作进行同步了,但是官方api示例为什么要自己手动添加同步呢?

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

查看Collections.synchronizedList的源代码

SynchronizedCollection(Collection c) { 
      if (c==null) 
        throw new NullPointerException(); 
    this.c = c; 
      mutex = this; 
    } 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class MyArrayList {
	/** 
   * 创建一个列表,一个线程进行写入,一个线程读取 iterator 和 listIterator 方法返回的迭代器是快速失败的 
   */
	public void readWrite() {
		List nums = new ArrayList();
		List synNums = Collections.synchronizedList(nums);
		//启动写入线程 
		new WriteListThread(synNums).start();
		//启动删除线程 
		new DeleteListThread(synNums).start();
	}
	public static void main(String[] args) {
		new MyArrayList().readWrite();
	}
}
class WriteListThread extends Thread {
	private List nums;
	public WriteListThread(List nums) {
		super("WriteListThread");
		this.nums = nums;
	}
	// 不停写入元素1 
	public void run() {
		while (true) {
			nums.add(new Random().nextint(1000));
			System.out.println(Thread.currentThread().getName());
		}
	}
}
class DeleteListThread extends Thread {
	private List nums;
	public DeleteListThread(List nums) {
		super("DeleteListThread");
		this.nums = nums;
	}
	// 删除第一个元素 
	public void run() {
		while (true) {
			try{
				System.out.println(Thread.currentThread().getName()+":"+nums.remove(0));
			}
			catch(Exception e){
				continue ;
			}
		}
	}
}

可见对于集合同步操作,使用Collections的同步包装工具类,还需要对非原子操作用户还需要手动进行同步

如下所示,加一个线程,对集合进行读取

class ReadListThread extends Thread {
	private List nums;
	public ReadListThread(List nums) {
		super(“ReadListThread”);
		this.nums = nums;
	}
	// 不停读取元素,非原子操作,则需要手动加上锁 
	public void run() {
		while (true) {
			//休眠,将锁交给其他线程 
			try {
				Thread.sleep(1000);
			}
			catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			synchronized (nums) {
				if (nums.size() > 100) {
					Iterator iter = nums.iterator();
					while (iter.hasNext()) {
						System.out.println(Thread.currentThread().getName() 
						                + ”:” + iter.next());
						;
					}
				} else{
					try {
						nums.wait(1000);
					}
					catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}

热门栏目