JDK中Collections的线程安全怎么实现(collections,jdk,编程语言)

时间:2024-05-07 07:44:02 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

    JDK%E4%B8%ADCollections%E7%9A%84%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E6%80%8E%E4%B9%88%E5%AE%9E%E7%8E%B0

方法:

publicstatic<T>Set<T>synchronizedSet(Set<T>s){

returnnewSynchronizedSet<T>(s);

}

staticclassSynchronizedSet<E>

extendsSynchronizedCollection<E>

implementsSet<E>{

privatestaticfinallongserialVersionUID=487447009682186044L;


SynchronizedSet(Set<E>s){

super(s);

}

SynchronizedSet(Set<E>s,Objectmutex){

super(s,mutex);

}


publicbooleanequals(Objecto){

synchronized(mutex){returnc.equals(o);}

}

publicinthashCode(){

synchronized(mutex){returnc.hashCode();}

}

}


//useserialVersionUIDfromJDK1.2.2forinteroperability

privatestaticfinallongserialVersionUID=3053995032091335093L;


finalCollection<E>c;//BackingCollection

finalObjectmutex;//Objectonwhichtosynchronize


SynchronizedCollection(Collection<E>c){

if(c==null)

thrownewNullPointerException();

this.c=c;

mutex=this;

}

SynchronizedCollection(Collection<E>c,Objectmutex){

this.c=c;

this.mutex=mutex;

}


publicintsize(){

synchronized(mutex){returnc.size();}

}

publicbooleanisEmpty(){

synchronized(mutex){returnc.isEmpty();}

}

publicbooleancontains(Objecto){

synchronized(mutex){returnc.contains(o);}

}

publicObject[]toArray(){

synchronized(mutex){returnc.toArray();}

}

public<T>T[]toArray(T[]a){

synchronized(mutex){returnc.toArray(a);}

}


publicIterator<E>iterator(){

returnc.iterator();//Mustbemanuallysynchedbyuser!

}


publicbooleanadd(Ee){

synchronized(mutex){returnc.add(e);}

}

publicbooleanremove(Objecto){

synchronized(mutex){returnc.remove(o);}

}


publicbooleancontainsAll(Collection<?>coll){

synchronized(mutex){returnc.containsAll(coll);}

}

publicbooleanaddAll(Collection<?extendsE>coll){

synchronized(mutex){returnc.addAll(coll);}

}

publicbooleanremoveAll(Collection<?>coll){

synchronized(mutex){returnc.removeAll(coll);}

}

publicbooleanretainAll(Collection<?>coll){

synchronized(mutex){returnc.retainAll(coll);}

}

publicvoidclear(){

synchronized(mutex){c.clear();}

}

publicStringtoString(){

synchronized(mutex){returnc.toString();}

}

privatevoidwriteObject(ObjectOutputStreams)throwsIOException{

synchronized(mutex){s.defaultWriteObject();}

}

}

List和Map方法同理,这样,我们利用了装实模式,给我们的Map和List穿上了交通协管员的制服,减少了类爆炸,这就是装实模式;

packageorg;


publicclassAImpimplementsIA{


publicsynchronizedvoidsay(){

;

}


}


packageorg;


publicinterfaceIA{

publicvoidsay();

}


sychronized标识符是不影响接口的实现和继承的

本文:JDK中Collections的线程安全怎么实现的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:怎么在maven中将springboot打成jar包下一篇:

2 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18