我们在对前面的几个聚集类进行分析的时候,我们发现,聚集类是一个curd很频繁的类,那么,他就不可避免的涉及到线程安全的问题,我们知道Vector是线程安全的,但是,其他的类,怎么能让他达到线程安全的地步呢,我们就不得不拉出Collections类来;其中有三个精彩的方法:
- public static <T> Set<T> synchronizedSet(Set<T> s) {
- return new SynchronizedSet<T>(s);
- }
- static class SynchronizedSet<E>
- extends SynchronizedCollection<E>
- implements Set<E> {
- private static final long serialVersionUID = 487447009682186044L;
- SynchronizedSet(Set<E> s) {
- super(s);
- }
- SynchronizedSet(Set<E> s, Object mutex) {
- super(s, mutex);
- }
- public boolean equals(Object o) {
- synchronized(mutex) {return c.equals(o);}
- }
- public int hashCode() {
- synchronized(mutex) {return c.hashCode();}
- }
- }
- // use serialVersionUID from JDK 1.2.2 for interoperability
- private static final long serialVersionUID = 3053995032091335093L;
- final Collection<E> c; // Backing Collection
- final Object mutex; // Object on which to synchronize
- SynchronizedCollection(Collection<E> c) {
- if (c==null)
- throw new NullPointerException();
- this.c = c;
- mutex = this;
- }
- SynchronizedCollection(Collection<E> c, Object mutex) {
- this.c = c;
- this.mutex = mutex;
- }
- public int size() {
- synchronized(mutex) {return c.size();}
- }
- public boolean isEmpty() {
- synchronized(mutex) {return c.isEmpty();}
- }
- public boolean contains(Object o) {
- synchronized(mutex) {return c.contains(o);}
- }
- public Object[] toArray() {
- synchronized(mutex) {return c.toArray();}
- }
- public <T> T[] toArray(T[] a) {
- synchronized(mutex) {return c.toArray(a);}
- }
- public Iterator<E> iterator() {
- return c.iterator(); // Must be manually synched by user!
- }
- public boolean add(E e) {
- synchronized(mutex) {return c.add(e);}
- }
- public boolean remove(Object o) {
- synchronized(mutex) {return c.remove(o);}
- }
- public boolean containsAll(Collection<?> coll) {
- synchronized(mutex) {return c.containsAll(coll);}
- }
- public boolean addAll(Collection<? extends E> coll) {
- synchronized(mutex) {return c.addAll(coll);}
- }
- public boolean removeAll(Collection<?> coll) {
- synchronized(mutex) {return c.removeAll(coll);}
- }
- public boolean retainAll(Collection<?> coll) {
- synchronized(mutex) {return c.retainAll(coll);}
- }
- public void clear() {
- synchronized(mutex) {c.clear();}
- }
- public String toString() {
- synchronized(mutex) {return c.toString();}
- }
- private void writeObject(ObjectOutputStream s) throws IOException {
- synchronized(mutex) {s.defaultWriteObject();}
- }
- }
List和Map方法同理,这样,我们利用了装实模式,给我们的Map和List穿上了交通协管员的制服,减少了类爆炸,这就是装实模式;
- package org;
- public class AImp implements IA {
- public synchronized void say() {
- ;
- }
- }
- package org;
- public interface IA {
- public void say();
- }
sychronized标识符是不影响接口的实现和继承的;