|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
因为能用到多少功能就用多少,不能用就不用!总的来说:要简单要性能好,可以不用框架。你说java复杂,就是因为你把java(j2ee)与这些框架混在了一起。StreamingDataBetweenThreadsUsingPipes
Thejava.iopackageprovidesmanyclassesforwritingandreadingdatatoandfromstreams.Mostofthetime,thedataiswrittentoorreadfromafileornetworkconnection.Insteadofstreamingdatatoafile,athreadcanstreamitthroughapipetoanotherthread.Thefirstthreadwritestothepipe,andthesecondthreadreadsfromthepipe.Apipeisneitherafilenoranetworkconnection,butastructureinmemorythatholdsthedatathatiswrittenuntilitisread.Usually,apipehasafixedcapacity.Whenthepipeisfilledtothiscapacity,attemptstowritemoredatawillblockwaitinguntilsomedataisdrained(read)fromthepipebyanotherthread.Similarly,whenapipeisempty,attemptstoreaddatafromthepipewillblockwaitinguntilanotherthreadwritessomedataintoit.
线程间可以经由过程pipe传送数据。Pipe不是文件也不是收集毗连,它是内存中的一种数据布局,能保留数据守候读取。
Therearefourpipe-relatedclassesinthejava.iopackagethatcanbeusedtostreamdatabetweenthreads:PipedInputStream,PipedOutputStream,PipedReader,andPipedWriter.APipedInputStreamandaPipedOutputStreamarehookedtogethertotransferbytesbetweenthreads.APipedReaderandaPipedWriterarehookedtogethertotransfercharacterdatabetweenthreads.Figure8.5showstheclassdiagramfortheseclasses.ThePipedOutputStreamobjectkeepsareferencetothePipedInputStreamobjectitisconnectedto.Similarly,thePipedWriterobjectkeepsareferencetothePipedReaderobjectitisconnectedto.
Java.io包中供应了四种pipe相干的类用来在线程间streamdata:PipedInputStream,PipedOutputStream,PipedReader,PipedWriter。PipedInputStream,PipedOutputStream相分离传输bytes,PipedReader,PipedWriter组和传输character。PipedOutputStream保留着PipedInputStream的一个援用,PipedWriter保留着PipedReader的一个援用。
ApipemadeupofaPipedInputStreamandaPipedOutputStreamhasacapacitytohold1024bytes.Thismeansthatthethreaddoingthewritingcanbeupto1024bytesaheadofthethreaddoingthereading.Thisbufferingmakesthetransferofdatamoreefficientthanasingle-bytehandoffwouldbe.ApipemadeupofaPipedReaderandaPipedWriterhasacapacitytohold1024characters.Again,thisbufferingallowsthethreaddoingthewritingtoworkalittlebitaheadofthethreaddoingthereading.Idiscoveredthesizeofthepipes(1024bytesand1024characters)byexaminingthesourcecodefromSunMicrosystems.TheAPIdocumentationgivesnoinformationorguaranteesregardingtheinternalpipesize.Therefore,youshouldnotdependon1024beingtheuniversalsize.
研讨源码发明发明pipe的缓冲区为1024bytes/characters,但javaAPI文档中并没有明白给出相干信息。以是,实践编程时不必要思索缓冲区巨细。
PipedInputStreamandPipedOutputStreameachrepresentanendofthepipeandneedtobeconnectedtoeachotherbeforedatacanbesent.BothPipedInputStreamandPipedOutputStreamhaveaconstructorthattakesareferencetotheother.Itdoesn’tmatterwhichisconstructedfirst.Youcanwriteeither
PipedInputStreamandPipedOutputStream代表了pipe的两头,必要相互毗连来发送数据。他们都有一个机关函数来保留对方的援用,可是没有前后按次。
PipedInputStreampipeIn=newPipedInputStream();
PipedOutputStreampipeOut=newPipedOutputStream(pipeIn);
Or
PipedOutputStreampipeOut=newPipedOutputStream();
PipedInputStreampipeIn=newPipedInputStream(pipeOut);
Additionally,bothendscanbecreatedwiththeirzero-argumentconstructorsandconnectedtogetherwithconnect().Youcanwriteeither
同时,还供应了connect()办法来创建两头的毗连
PipedInputStreampipeIn=newPipedInputStream();
PipedOutputStreampipeOut=newPipedOutputStream();
pipeIn.connect(pipeOut);
or
PipedInputStreampipeIn=newPipedInputStream();
PipedOutputStreampipeOut=newPipedOutputStream();
pipeOut.connect(pipeIn);
Iftheendsofthepipearenotyetconnectedtoeachother,anyattempttoreadorwritewillcauseanIOExceptiontobethrown.Becauseofthis,it’sgenerallyagoodideatoconnecttheendsrightawaybyusingtheconstructor.PipedReaderandPipedWriterconnecttoeachotherinthesamewaysthatPipedInputStreamandPipedOutputStreamdo,sothesamerulesandguidelinesapply.
假如两头没有毗连便读取数据,会抛出IOException非常。以是,最幸亏机关函数中便创建毗连。PipedReaderandPipedWriter也是一样的情形。
PipedBytes
/*
*Createdon2005-7-15
*
*JavaThreadProgramming-PaulHyde
*Copyright?1999SamsPublishing
*JonathanQ.Bo进修条记
*
*/
packageorg.tju.msnrl.jonathan.thread.chapter8;
importjava.io.*;
/**
*@authorJonathanQ.BofromTJUMSNRL
*
*Email:jonathan.q.bo@gmail.com
*Blog:blog.csdn.net/jonathan_q_bo
*blog.yesky.net/jonathanundersun
*
*EnjoyLifewithSun!
*
*/
publicclassPipeBytes{
publicPipeBytes(){
}
publicstaticvoidwriteStuff(OutputStreamrawout){
try{
DataOutputStreamout=newDataOutputStream(newBufferedOutputStream(rawout));
int[]data={99,90,34,56,767,78,234,53,67,89,123};
for(inti=0;i<data.length;i++){
out.writeInt(data[i]);
}
out.flush();
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidreadStuff(InputStreamrawin){
try{
DataInputStreamin=newDataInputStream(newBufferedInputStream(rawin));
booleaneof=false;
while(!eof){
try{
inti=in.readInt();
System.out.println("hasread:"+i);
}catch(EOFExceptione1){
eof=true;
}
}
System.out.println("Readall");
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
try{
finalPipedOutputStreamout=newPipedOutputStream();
finalPipedInputStreamin=newPipedInputStream(out);
RunnablerunA=newRunnable(){
publicvoidrun(){
writeStuff(out);
}
};
ThreadthreadA=newThread(runA,"threadA");
threadA.start();
RunnablerunB=newRunnable(){
publicvoidrun(){
readStuff(in);
}
};
ThreadthreadB=newThread(runB,"threadB");
threadB.start();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
输入了局:
hasread:99
hasread:90
hasread:34
hasread:56
hasread:767
hasread:78
hasread:234
hasread:53
hasread:67
hasread:89
hasread:123
Readall
PipedCharacters
/*
*Createdon2005-7-15
*
*JavaThreadProgramming-PaulHyde
*Copyright?1999SamsPublishing
*JonathanQ.Bo进修条记
*
*/
packageorg.tju.msnrl.jonathan.thread.chapter8;
importjava.io.*;
/**
*@authorJonathanQ.BofromTJUMSNRL
*
*Email:jonathan.q.bo@gmail.com
*Blog:blog.csdn.net/jonathan_q_bo
*blog.yesky.net/jonathanundersun
*
*EnjoyLifewithSun!
*
*/
publicclassPipeCharacters{
publicPipeCharacters(){
}
publicstaticvoidwriteStuff(WriterrawOut){
try{
BufferedWriterout=newBufferedWriter(rawOut);
String[][]line={
{"java","multithread","programming"},
{"its","very","intrested"},
{"i","love","it"},
{"ha","ha","ha"}
};
/*输入,每行*/
for(inti=0;i<line.length;i++){
String[]word=line[i];
/*每行中的每一个单词*/
for(intj=0;j<word.length;j++){
if(j>0)
out.write("");//加上空格
out.write(word[j]);//输入单词
}
out.newLine();//换行
}
out.flush();
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidreadStuff(ReaderrawIn){
try{
BufferedReaderin=newBufferedReader(rawIn);
Stringline;
while((line=in.readLine())!=null){
System.out.println("hasread"+line);
}
System.out.println("Readall");
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
try{
finalPipedWriterout=newPipedWriter();
finalPipedReaderin=newPipedReader(out);
RunnablerunA=newRunnable(){
publicvoidrun(){
writeStuff(out);
}
};
ThreadthreadA=newThread(runA,"threadA");
threadA.start();
RunnablerunB=newRunnable(){
publicvoidrun(){
readStuff(in);
}
};
ThreadthreadB=newThread(runB,"threadB");
threadB.start();
}catch(Exceptione){
e.printStackTrace();
}
}
}
输入了局:
hasreadjavamultithreadprogramming
hasreaditsveryintrested
hasreadiloveit
hasreadhahaha
Readall
UsingThreadLocalandInheritableThreadLocal
Thevaluereturnedfromtheget()methodThreadLocaldependsonwhichthreadinvokesthemethod.InheritableThreadLocalallowsthesevaluestobeinheritedfromparenttochildthread.
ThreadLocalcontainsareferencetoaWeakHashMapthatholdskey-valuepairs.WeakreferenceswereintroducedinJDK1.2,andWeakHashMaptakesadvantageofthemtoautomaticallyremovemappingsforthreadsthathavediedandbeende-referencedinallotherplaces.Thisway,ThreadLocaldoesnotkeeptrackofvaluesforthreadsthathavelongsincedied.IntheWeakHashMap,thelookupkeyisthereferencetotheThreadandthevaluestoredisaThreadLocal.Entryobject.ThreadLocal.EntryisaninnerclasstoThreadLocalandisusedbyThreadLocaltostorethethread-specificvalues.
InheritableThreadLocalisasubclassofThreadLocalthatprovidesamechanismforthethread-specificvariabletobeinheritedfromparentthreadtochildthread.InheritableThreadLocal.EntryisasubclassofThreadLocal.Entryandisalsoaninnerclass.ThreadcontainsaprivatereferencetoanInheritableThreadLocal.Entryobjectandusesittopassthethread-specificvariabledownfromparentthreadtochildthreadwhenanewthreadiscreated.
ThreadLocal内置WeakHashMap保留Thread和ThreadLocal.Entry(外部类,保留了线程标识值,不是线程名)。InheritableThreadLocal是ThreadLocal的子类,供应了子父线程间线程标识的承继机制。
ThreadLocalAPI
ThreadLocalhastwopublicmethods.Thefirstoneisget():
publicObjectget()
get()isusedtoretrievethethread-specificvalue.Internally,itlooksuptoseeifthecallingthreadhasavaluestored.Ifisdoes,itreturnsthatvalue.Ifnot,itcallstheprotectedmethodinitialValue()toinitializeavalueforthecallingthread,storesitintheinternalWeakHashMapforfuturelookups,andreturnsthevaluetothecaller.Typically,get()istheonlymethodcalledonaThreadLocalobject.
publicvoidset(Objectvalue)
set()takesthevaluepassedandstoresitintheinternalWeakHashMapforfuturelookups.
ThreadLocalisnotabstract,butitgenerallyneedstobesubclassedtobeuseful.Thisprotectedmethodshouldbeoverriddeninthesubclass:
protectedObjectinitialValue()
Bydefault,initialValue()returnsnull,butinthesubclassitcanreturnamoremeaningfulvalue.
get()办法用来取得挪用此办法的线程的线程标识。挪用时,起首查找是不是存在此线程的援用,假如有,则前往key/value对中的线程标识,假如没有,则挪用protectedinitialValue()办法,构成此线程标识,保留在WeakHaspMap中待用。默许情形下,initialValue()办法前往null。
ThreadID
ThreadId.java
/*
*Createdon2005-7-15
*
*JavaThreadProgramming-PaulHyde
*Copyright?1999SamsPublishing
*JonathanQ.Bo进修条记
*
*/
packageorg.tju.msnrl.jonathan.thread.chapter8;
/**
*@authorJonathanQ.BofromTJUMSNRL
*
*Email:jonathan.q.bo@gmail.com
*Blog:blog.csdn.net/jonathan_q_bo
*blog.yesky.net/jonathanundersun
*
*EnjoyLifewithSun!
*
*/
publicclassThreadIdextendsThreadLocal{
privateintnextId;
publicThreadId(){
nextId=10001;
}
privatesynchronizedIntegergetNewId(){
Integerid=newInteger(nextId);
nextId++;
returnid;
}
protectedObjectinitialValue(){
print("initialvalue");
returngetNewId();
}
publicintgetThreadId(){
Integerid=(Integer)get();
returnid.intValue();
}
publicvoidprint(Stringmsg){
Stringtemp=Thread.currentThread().getName();
System.out.println(temp+"-"+msg);
}
}
ThreadIdMain.java
/*
*Createdon2005-7-15
*
*JavaThreadProgramming-PaulHyde
*Copyright?1999SamsPublishing
*JonathanQ.Bo进修条记
*
*/
packageorg.tju.msnrl.jonathan.thread.chapter8;
/**
*@authorJonathanQ.BofromTJUMSNRL
*
*Email:jonathan.q.bo@gmail.com
*Blog:blog.csdn.net/jonathan_q_bo
*blog.yesky.net/jonathanundersun
*
*EnjoyLifewithSun!
*
*/
publicclassThreadIdMainimplementsRunnable{
privateThreadIdvar;
publicThreadIdMain(ThreadIdvar){
this.var=var;
}
publicvoidrun(){
try{
print("getthreadid:"+var.getThreadId());
Thread.sleep(2000);
print("secondgetthreadid:"+var.getThreadId());
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
publicvoidprint(Stringmsg){
Stringtemp=Thread.currentThread().getName();
System.out.println(temp+"-"+msg);
}
publicstaticvoidmain(String[]args){
ThreadIdtId=newThreadId();
ThreadIdMainshare=newThreadIdMain(tId);
try{
ThreadthreadA=newThread(share,"threadA");
threadA.start();
Thread.sleep(500);
ThreadthreadB=newThread(share,"threadB");
threadB.start();
Thread.sleep(500);
ThreadthreadC=newThread(share,"threadC");
threadC.start();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
输入了局:
threadA-initialvalue
threadA-getthreadid:10001
threadB-initialvalue
threadB-getthreadid:10002
threadC-initialvalue
threadC-getthreadid:10003
threadA-secondgetthreadid:10001
threadB-secondgetthreadid:10002
threadC-secondgetthreadid:10003
InheritableThreadLocalAPI
InheritableThreadLocalisasubclassofThreadLocalandallowsathread-specificvaluetobeinheritedfromtheparentthreadtothechildthread.TherearenotanypublicmethodsonInheritableThreadLocal.ItcanbeuseddirectlyasaspecialkindofThreadLocalthatpassesitsvaluefromparentthreadtochildthread.
Ifyoudon’twanttousetheparentthread’svaluedirectly,youcanoverride
protectedObjectchildValue(ObjectparentValue)
toproduceacustomizedchildvalueatthetimethatthechildthreadiscreated.Bydefault,childValue()simplyreturnsparentValue.
InheritableThreadLocal父线程向子线程传送线程标识,在此类中无public办法,默许子父线程具有不异的线程标识。假如要定制子线程标识,则overridechildValue(ObjectparentValue)办法。
InheritableThreadID
/*
*Createdon2005-7-15
*
*JavaThreadProgramming-PaulHyde
*Copyright?1999SamsPublishing
*JonathanQ.Bo进修条记
*
*/
packageorg.tju.msnrl.jonathan.thread.chapter8;
/**
*@authorJonathanQ.BofromTJUMSNRL
*
*Email:jonathan.q.bo@gmail.com
*Blog:blog.csdn.net/jonathan_q_bo
*blog.yesky.net/jonathanundersun
*
*EnjoyLifewithSun!
*
*/
publicclassInheritableThreadId{
publicstaticfinalintUNIQUE=101;
publicstaticfinalintINHERIT=102;
publicstaticfinalintSUFFIX=103;
privateThreadLocalthreadLocal;
privateintnextId;
publicInheritableThreadId(inttype){
nextId=201;
switch(type){
caseUNIQUE:
threadLocal=newThreadLocal(){
protectedObjectinitialValue(){
print("unique...initialvalue");
returngetNewId();
}
};
break;
caseINHERIT:
threadLocal=newInheritableThreadLocal(){
protectedObjectinitialValue(){
print("inherit...initialvalue");
returngetNewId();
}
};
break;
caseSUFFIX:
threadLocal=newInheritableThreadLocal(){
protectedObjectinitialValue(){
print("suffix...initialvalue");
returngetNewId();
}
protectedObjectchildValue(ObjectparentValue){
print("suffix...childvalue");
returnparentValue+"-CH";
}
};
break;
default:
break;
}
}
publicstaticRunnablecreateTarget(InheritableThreadIdid){
finalInheritableThreadIdvar=id;
RunnablepRun=newRunnable(){
publicvoidrun(){
print("var.getId():"+var.getId());
RunnablecRun=newRunnable(){
publicvoidrun(){
print("var.getId():"+var.getId());
}
};
ThreadpThread=Thread.currentThread();
StringpName=pThread.getName();
print(pName+"createachildthread"+pName+"-CHILD");
ThreadcThread=newThread(cRun,pName+"-CHILD");
cThread.start();
}
};
returnpRun;
}
privatesynchronizedStringgetNewId(){
Stringid="ID"+this.nextId;
nextId++;
returnid;
}
publicStringgetId(){
return(String)this.threadLocal.get();
}
publicstaticvoidprint(Stringmsg){
Stringtemp=Thread.currentThread().getName();
System.out.println(temp+"-"+msg);
}
publicstaticvoidmain(String[]args){
try{
System.out.println("=======ThreadLocal=======");
InheritableThreadIdvarA=newInheritableThreadId(UNIQUE);
RunnabletargetA=createTarget(varA);
ThreadthreadA=newThread(targetA,"threadA");
threadA.start();
Thread.sleep(500);
System.out.println("
===InheritableThreadLocal===");
InheritableThreadIdvarB=newInheritableThreadId(INHERIT);
RunnabletargetB=createTarget(varB);
ThreadthreadB=newThread(targetB,"threadB");
threadB.start();
Thread.sleep(500);
System.out.println("
=InheritableThreadLocal,custumchildValue=");
InheritableThreadIdvarC=newInheritableThreadId(SUFFIX);
RunnabletargetC=createTarget(varC);
ThreadthreadC=newThread(targetC,"threadC");
threadC.start();
}catch(InterruptedExceptione1){
e1.printStackTrace();
}
}
}
输入了局:
=======ThreadLocal=======
threadA-unique...initialvalue
threadA-var.getId():ID201
threadA-threadAcreateachildthreadthreadA-CHILD
threadA-CHILD-unique...initialvalue
threadA-CHILD-var.getId():ID202
===InheritableThreadLocal===
threadB-inherit...initialvalue
threadB-var.getId():ID201
threadB-threadBcreateachildthreadthreadB-CHILD
threadB-CHILD-var.getId():ID201
=InheritableThreadLocal,custumchildValue=
threadC-suffix...initialvalue
threadC-var.getId():ID201
threadC-threadCcreateachildthreadthreadC-CHILD
threadC-suffix...childvalue
threadC-CHILD-var.getId():ID201-CH
令人可喜的是java现在已经开源了,所以我想我上述的想法也许有一天会实现,因为java一直都是不断创新的语言,每次创新都会给我们惊喜,这也是我喜欢java的一个原因。 |
|