JAVA编程:Java Thread Programming 1.8.4 - Inte...
因为能用到多少功能就用多少,不能用就不用!总的来说:要简单要性能好,可以不用框架。你说java复杂,就是因为你把java(j2ee)与这些框架混在了一起。StreamingDataBetweenThreadsUsingPipesThejava.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);
}
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;
/*每行中的每一个单词*/
for(intj=0;j<word.length;j++){
if(j>0)
out.write("");//加上空格
out.write(word);//输入单词
}
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的一个原因。 Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台 你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。 多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。 是一种为 Internet发展的计算机语言 是一种语言,用以产生「小应用程序(Applet(s)) 一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。 自从Sun推出Java以来,就力图使之无所不包,所以Java发展到现在,按应用来分主要分为三大块:J2SE,J2ME和J2EE,这也就是Sun ONE(Open Net Environment)体系。J2SE就是Java2的标准版,主要用于桌面应用软件的编程;J2ME主要应用于嵌入是系统开发,如手机和PDA的编程;J2EE是Java2的企业版,主要用于分布式的网络程序的开发,如电子商务网站和ERP系统。 你快去找一份Java的编程工作来做吧(如果是在校学生可以去做兼职啊),在实践中提高自己,那才是最快的。不过你得祈祷在公司里碰到一个高手,而且他 还愿意不厌其烦地教你,这样好象有点难哦!还有一个办法就是读开放源码的程序了。我们知道开放源码大都出自高手,他们设计合理,考虑周到,再加上有广大的程序员参与,代码的价值自然是字字珠叽,铿锵有力(对不起,偶最近《金装四大才子》看多了)。 其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。 应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展 让你能够真正掌握接口或抽象类的应用,从而在原来的Java语言基础上跃进一步,更重要的是,设计模式反复向你强调一个宗旨:要让你的程序尽可能的可重用。 Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台 Java 编程语言的风格十分接近C、C++语言。 多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。 《JAVA语言程序设计》或《JAVA从入门到精通》这两本书开始学,等你编程有感觉的时候也可以回看一下。《JAVA读书笔记》这本书,因为讲的代码很多,也很容易看懂,涉及到面也到位。是你学习技术巩固的好书,学完后就看看《JAVA编程思想》这本书,找找一个自己写的代码跟书上的代码有什么不一样。 设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧 Java 编程语言的风格十分接近C、C++语言。 吧,现在很流行的Structs就是它的一种实现方式,不过Structs用起来实在是很繁,我们只要学习其精髓即可,我们完全可以设计自己的MVC结构。然后你再研究一下软件Refactoring (重构)和极限XP编程,相信你又会上一个台阶。 做完这些,你不如整理一下你的Java代码,把那些经典的程序和常见的应用整理出来,再精心打造一番,提高其重用性和可扩展性。你再找几个志同道合的朋友成立一个工作室吧
页:
[1]