JDK中Collections的线程安全怎么实现
这篇“JDK中Collections的线程安全怎么实现”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JDK中Collections的线程安全怎么实现”文章吧。
创新互联建站专业为企业提供临清网站建设、临清做网站、临清网站设计、临清网站制作等企业网站建设、网页设计与制作、临清企业网站模板建站服务,十余年临清做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
方法:
public static
Set synchronizedSet(Set s) { return new SynchronizedSet
(s); }
static class SynchronizedSet
extends SynchronizedCollection
implements Set
{ private static final long serialVersionUID = 487447009682186044L;
SynchronizedSet(Set
s) { super(s);
}
SynchronizedSet(Set
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
c; // Backing Collection final Object mutex; // Object on which to synchronize
SynchronizedCollection(Collection
c) { if (c==null)
throw new NullPointerException();
this.c = c;
mutex = this;
}
SynchronizedCollection(Collection
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[] toArray(T[] a) { synchronized(mutex) {return c.toArray(a);}
}
public Iterator
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标识符是不影响接口的实现和继承的
以上就是关于“JDK中Collections的线程安全怎么实现”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注创新互联行业资讯频道。
本文题目:JDK中Collections的线程安全怎么实现
标题来源:http://ybzwz.com/article/goijge.html