資源描述:
《java實驗歸納總結(jié).doc》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、1.設(shè)計一個Person類,包含:姓名,年齡,性別。要求:該類至多只能創(chuàng)建一男、一女兩個對象。2.設(shè)計一個測試類Test,創(chuàng)建若干個Person類對象,測試是否符合要求。packagetest8;classperson{Stringname;intage;charsex;staticintflag1=1,flag2=1;privateperson(Stringn,inta,chars){name=n;age=a;sex=s;if(s=='m'){flag1--;}if(s=='f'){flag2--;}}publicstaticpersonnewperson(Stri
2、ngn,inta,chars){if(s=='m'&&flag1!=0){personp=newperson(n,a,s);returnp;}elseif(s=='f'&&flag2!=0){personp=newperson(n,a,s);returnp;}else{returnnull;}}publicStringtoString(){return("name:"+name+"age:"+age+"sex:"+sex);}}publicclasstest{publicstaticvoidmain(String[]args){personp1,p2,p3;p1=pe
3、rson.newperson("mary",11,'f');p2=person.newperson("tom",14,'m');p3=person.newperson("jane",13,'f');System.out.println(p1);System.out.println(p2);System.out.println(p3);}}1.設(shè)計一個數(shù)據(jù)單元類DataUnit,它包含學(xué)號(Number)和姓名(Name)兩個數(shù)據(jù)成員。2.設(shè)計兩個線程,一個線程往數(shù)據(jù)單元里寫信息,一個線程從數(shù)據(jù)單元里讀信息。要求使用線程同步技術(shù),使得每寫一次就往外讀一次。例如,寫和讀的
4、數(shù)據(jù)序列為:Write:1,Name1Read:1,Name1Write:2,Name2Read:2,Name2...packagetest7;classDataUnit{intnumber;Stringname;intmax;booleanflag=false;publicDataUnit(intnumber,Stringname,intmax){this.name=name;this.max=max;}publicsynchronizedvoidin(){if(flag){try{wait();}catch(Exceptione){}}System.out.pri
5、ntln("Writenumber:"+(++number)+"writename:"+(number));flag=true;notify();}publicsynchronizedvoidout(){if(!flag){try{wait();}catch(Exceptione){}}System.out.println("readnumber:"+(number)+"readname:"+(number));flag=false;notify();}}classwriteextendsThread{DataUnitx=null;publicwrite(DataUn
6、itx){this.x=x;}publicvoidrun(){while(x.number7、();newread(x).start();}}設(shè)計一個線程Thread類的子類DataThread,使用DataThread構(gòu)建兩個線程,分別輸出50以內(nèi)的奇數(shù)和偶數(shù),并使兩個線程并發(fā)執(zhí)行。packagetest6;classdatathreadextendsThread{privateintnumber;Stringflag;publicdatathread(intnum){number=num;if(number==-2)flag="even";elseflag="odd";}publicvoidrun(){intresult=number;S