版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1.Java初學(xué)者第一個(gè)小程序publicclassHelloWorld{publicstaticvoidmain(String[]args){System.out.println("HelloWorld!");}}2.break練習(xí)publicclassTestBreak{publicstaticvoidmain(String[]args){intstop=4;for(inti=1;i<=10;i++){if(i==stop){break;}else{System.out.println(i);}}}}3.continue練習(xí)publicclassTestContinute{publicstaticvoidmain(String[]args){intcon=3;for(inti=1;i<=5;i++){if(i==con){continue;}else{System.out.println(i);}}}}4.使用非遞歸的方法求Fibonacci數(shù)列第5個(gè)數(shù)是多少?//1,1,2,3,5,8,13publicclassTestFab{publicstaticvoidmain(String[]args){System.out.println(method(5));}publicstaticlongmethod(intindex){if(index==1||index==2){return1;}longf1=1L;longf2=1L;longf=0;for(inti=0;i<index-2;i++){f=f1+f2;f1=f2;f2=f;}returnf;}}5.使用遞歸求Fibonacci數(shù)列第5個(gè)數(shù)是多少?答:5publicclassTestFibonacci{publicstaticvoidmain(String[]args){System.out.println(method(5));}publicstaticintmethod(intn){if(n==1||n==2){return1;}else{returnmethod(n-1)+method(n-2);}}}6.使用for循環(huán)求1!+2!+3!+......+10!=4037913;publicclassTestFor1{publicstaticvoidmain(String[]args){longf=1L;longresult=0;for(inti=1;i<=10;i++){f*=i;result+=f;}System.out.println(result);}}7.使用for循環(huán)求1+3+5+.....+99=2500;publicclassTestFor2{publicstaticvoidmain(String[]args){intresult=0;for(inti=1;i<=99;i+=2){result+=i;}System.out.println(result);}}8.if練習(xí)publicclassTestIF{publicstaticvoidmain(String[]args){inti=20;if(i<20){System.out.println("i<20");}elseif(i<40){System.out.println("i<40");}elseif(i>60){System.out.println("asf");}else{System.out.println("kasjfla");}}}9.使用遞歸求5!=120;publicclassTestJC{publicstaticvoidmain(String[]args){System.out.println(method(5));}publicstaticintmethod(intn){if(n==1){return1;}else{returnn*method(n-1);}}}10.方法的調(diào)用舉例publicclassTestMethod{publicstaticvoidmain(String[]args){m1();m2(5);m3(4,5);System.out.println(m4(4,6));}publicstaticvoidm1(){//return;System.out.println("OK");}publicstaticvoidm2(inti){if(i<3){return;}else{System.out.println(i);}}publicstaticvoidm3(inti,intj){System.out.println(i+j);}publicstaticintm4(inti,intj){returni<j?i:j;}}11.switch問題舉例,注意穿透現(xiàn)象publicclassTestSwitch{publicstaticvoidmain(String[]args){inti=3;switch(i){case3:System.out.println("A");break;case5:System.out.println("B");break;default:System.out.println("error");}}}12.whiledowhile舉例,將1到9輸出publicclassTestWhile{publicstaticvoidmain(String[]args){inti=1;while(i<=9){System.out.print(i+"");i++;}System.out.println();i=1;do{System.out.print(i+"");i++;}while(i<=9);}}13.求3維空間兩點(diǎn)坐標(biāo)之間的距離的平方classPoint{doublex;doubley;doublez;Point(doublex,doubley,doublez){this.x=x;this.y=y;this.z=z;}voidsetX(doublex){this.x=x;}voidsetY(doubley){this.y=y;}voidsetZ(doublez){this.z=z;}doublegetDistance(Pointp){return(x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)+(z-p.z)*(z-p.z);}}publicclassTestPoint{publicstaticvoidmain(String[]args){Pointp1=newPoint(1.0,2.0,3.0);Pointp2=newPoint(0.0,0.0,0.0);System.out.println(p1.getDistance(p2));p1.setY(1.0);System.out.println(p1.getDistance(newPoint(1.0,1.0,3.0)));}}14.重寫equals方法判定兩只貓是否相等publicclassTestEquals{publicstaticvoidmain(String[]args){Strings1="a";Strings2="a";System.out.println(s1==s2);System.out.println(s1.equals(s2));Strings3=newString("hello");Strings4=newString("hello");System.out.println(s3==s4);System.out.println(s3.equals(s4));Catc1=newCat(1,2,3);Catc2=newCat(1,2,3);System.out.println(c1==c2);System.out.println(c1.equals(c2));}}classCat{intcolor;intweight;intheight;Cat(intcolor,intweight,intheight){this.color=color;this.weight=weight;this.height=height;}publicbooleanequals(Objectobj){if(obj==null){returnfalse;}else{if(objinstanceofCat){Catc=(Cat)obj;if(this.color==c.color&&this.height==c.height&&this.weight==c.weight){returntrue;}}}returnfalse;}}15.多態(tài)舉例packagecom.dt;publicclassTestDt{publicstaticvoidmain(String[]args){Catc=newCat("catname","yellow");Dogd=newDog("dogname","black");Ladyl1=newLady("l1",c);Ladyl2=newLady("l2",d);l1.myPetEnjoy();l2.myPetEnjoy();}}classAnimal{privateStringname;Animal(Stringname){=name;}publicvoidenjoy(){System.out.println("動(dòng)物的叫聲......");}}classCatextendsAnimal{privateStringeyeColor;Cat(Stringn,StringeyeColor){super(n);this.eyeColor=eyeColor;}publicvoidenjoy(){System.out.println("貓的叫聲......");}}classDogextendsAnimal{privateStringfurColor;Dog(Stringn,StringfurColor){super(n);this.furColor=furColor;}publicvoidenjoy(){System.out.println("狗的叫聲......");}}classLady{privateStringname;privateAnimalpet;Lady(Stringname,Animalpet){=name;this.pet=pet;}publicvoidmyPetEnjoy(){pet.enjoy();}}16.冒泡排序publicclassBubbleSort{publicstaticvoidmain(String[]args){int[]a=newint[args.length];for(inti=0;i<args.length;i++){a[i]=Integer.parseInt(args[i]);}print(a);bubbleSort(a);print(a);}privatestaticvoidprint(int[]a){for(inti=0;i<a.length;i++){System.out.print(a[i]+"");}System.out.println();}privatestaticint[]bubbleSort(int[]a){for(inti=a.length-1;i>=1;i--){for(intj=0;j<=a.length-2;j++){if(a[j]>a[j+1]){inttemp=a[j];a[j]=a[j+1];a[j+1]=temp;}}}returna;}}17.使用數(shù)組數(shù)3退1:非面向?qū)ο蟮膶懛╬ublicclassCount3Quit{publicstaticvoidmain(String[]args){Boolean[]arr=newBoolean[500];for(inti=0;i<arr.length;i++){arr[i]=true;}intleftCount=arr.length;intcountNum=0;intindex=0;while(leftCount>1){if(arr[index]==true){countNum++;if(countNum==3){countNum=0;arr[index]=false;leftCount--;}}index++;if(index==arr.length){index=0;}}for(inti=0;i<arr.length;i++){if(arr[i]==true){System.out.println(i);}}}}18.面向?qū)ο蟮臄?shù)3退1publicclassCount3Quit2{publicstaticvoidmain(String[]args){KidCirclekc=newKidCircle(500);intcountNum=0;intleftCount=kc.count;Kidk=kc.first;while(leftCount>1){countNum++;if(countNum==3){countNum=0;kc.delete(k);}k=k.right;}}}classKid{intid;Kid(intid){this.id=id;}Kidleft;Kidright;}classKidCircle{intcount=0;Kidfirst,last;KidCircle(intn){for(inti=0;i<n;i++){add();}}voidadd(){Kidk=newKid(count);if(count<=0){first=k;last=k;k.left=k;k.right=k;}else{last.right=k;k.left=last;k.right=first;first.left=k;last=k;}count++;}voiddelete(Kidk){if(count<=0){return;}elseif(count==1){first=last=null;}else{k.left.right=k.right;k.right.left=k.left;if(k==first){first=k.right;}elseif(k==last){last=k.left;}}count--;}}19.選擇排序publicclassSelectionSort{publicstaticvoidmain(String[]args){int[]a=newint[args.length];for(inti=0;i<args.length;i++){a[i]=Integer.parseInt(args[i]);}print(a);selectionSort(a);print(a);}privatestaticvoidprint(int[]a){for(inti=0;i<a.length;i++){System.out.print(a[i]+"");}System.out.println();}privatestaticvoidselectionSort(int[]a){inttemp,k;for(inti=0;i<a.length;i++){k=i;for(intj=k+1;j<a.length;j++){if(a[k]>a[j]){k=j;}}if(k!=i){temp=a[i];a[i]=a[k];a[k]=temp;}}}}20.簡(jiǎn)單運(yùn)算器publicclassTestArgs{publicstaticvoidmain(String[]args){doubled1=Double.parseDouble(args[0]);doubled2=Double.parseDouble(args[2]);doubled=0;if(args[1].equals("+")){d=d1+d2;}elseif(args[1].equals("-")){d=d1-d2;}elseif(args[1].equals("x")){d=d1*d2;}elseif(args[1].equals("/")){d=d1/d2;}else{System.out.println("error");}System.out.println(d);}}21.?dāng)?shù)組拷貝練習(xí)publicclassTestArrayCopy{publicstaticvoidmain(String[]args){int[][]intArray={{1,2},{3,4,5},{6,7}};int[][]intArrayBak=newint[3][];System.arraycopy(intArray,0,intArrayBak,0,intArray.length);intArray[2][1]=100;for(inti=0;i<intArray.length;i++){for(intj=0;j<intArray[i].length;j++){System.out.print(intArray[i][j]+"");}System.out.println();}}}22.對(duì)日期排序publicclassTestDateSort{publicstaticvoidmain(String[]args){Date[]days=newDate[5];days[0]=newDate(2006,5,4);days[1]=newDate(2006,7,4);days[2]=newDate(2008,5,4);days[3]=newDate(2004,5,9);days[4]=newDate(2004,5,4);Dated=newDate(2006,7,4);Stringstr=String.valueOf(d);//str=d.toString();bubbleSort(days);for(inti=0;i<days.length;i++){System.out.println(days[i]);}System.out.println(binarySearch(days,d));}publicstaticDate[]bubbleSort(Date[]a){intlen=a.length;for(inti=len-1;i>=1;i--){for(intj=0;j<=i-1;j++){if(a[j].compare(a[j+1])>0){Datetemp=a[j];a[j]=a[j+1];a[j+1]=temp;}}}returna;}publicstaticintbinarySearch(Date[]days,Dated){if(days.length==0)return-1;intstartPos=0;intendPos=days.length-1;intm=(startPos+endPos)/2;while(startPos<=endPos){if(pare(days[m])==0)returnm;if(pare(days[m])>0){startPos=m+1;}if(pare(days[m])<0){endPos=m-1;}m=(startPos+endPos)/2;}return-1;}}classDate{intyear,month,day;Date(inty,intm,intd){year=y;month=m;day=d;}publicintcompare(Datedate){returnyear>date.year?1:year<date.year?-1:month>date.month?1:month<date.month?-1:day>date.day?1:day<date.day?-1:0;}publicStringtoString(){return"Year:Month:Day--"+year+"-"+month+"-"+day;}}23.二分法查找publicclassTestSearch{publicstaticvoidmain(String[]args){inta[]={1,3,6,8,9,10,12,18,20,34};inti=12;//System.out.println(search(a,i));System.out.println(binarySearch(a,i));}publicstaticintsearch(int[]a,intnum){for(inti=0;i<a.length;i++){if(a[i]==num)returni;}return-1;}publicstaticintbinarySearch(int[]a,intnum){if(a.length==0)return-1;intstartPos=0;intendPos=a.length-1;intm=(startPos+endPos)/2;while(startPos<=endPos){if(num==a[m])returnm;if(num>a[m]){startPos=m+1;}if(num<a[m]){endPos=m-1;}m=(startPos+endPos)/2;}return-1;}}24.將字符串Strings="1,2;3,4,5;6,7,8";分解成一個(gè)double的二維數(shù)組publicclassArrayParser{publicstaticvoidmain(String[]args){double[][]d;Strings="1,2;3,4,5;6,7,8";String[]sFirst=s.split(";");d=newdouble[sFirst.length][];for(inti=0;i<sFirst.length;i++){//System.out.println(sFirst[i]);String[]sSecond=sFirst[i].split(",");d[i]=newdouble[sSecond.length];for(intj=0;j<sSecond.length;j++){//System.out.println(sSecond[j]);d[i][j]=Double.parseDouble(sSecond[j]);}}for(inti=0;i<d.length;i++){for(intj=0;j<d[i].length;j++){System.out.println(d[i][j]);}}}}25.列出D:/A下邊所以的文件及文件夾importjava.io.*;publicclassFileList{publicstaticvoidmain(String[]args){Filef=newFile("d:/A");System.out.println(f.getName());tree(f,1);}privatestaticvoidtree(Filef,intlevel){Stringstr="";for(inti=0;i<level;i++){str+="";}File[]childs=f.listFiles();for(inti=0;i<childs.length;i++){System.out.println(str+childs[i].getName());if(childs[i].isDirectory()){tree(childs[i],level+1);}}}}26.枚舉舉例enumMyColor{red3,green,blue};publicclassTestEnum{publicstaticvoidmain(String[]args){MyColorm=MyColor.red3;longl1=3333333255252553L;inti=(int)l1;System.out.println(i);shorts=5;s=(short)(s+2);s+=2;switch(m){casered3:System.out.println(MyColor.red3);break;casegreen:System.out.println("B_green");break;caseblue:System.out.println("C_blue");break;default:System.out.println("error");break;}System.out.println(m.toString().intern()=="red3");}}27.創(chuàng)建文件java.txtimportjava.io.*;publicclassTestFile{publicstaticvoidmain(String[]args){Stringseperator=File.separator;StringfileName="naruto.txt";Stringdirectory="m1/m2";Filef=newFile(directory,fileName);if(f.exists()){System.out.println("文件名是:"+f.getAbsolutePath());System.out.println("文件大小是:"+f.length());}else{f.getParentFile().mkdirs();try{f.createNewFile();}catch(IOExceptione){e.printStackTrace();}}}}publicclassTestString1{publicstaticvoidmain(String[]args){Strings1="hello";Strings2="world";Strings3="hello";System.out.println(s1==s3);//trues1=newString("hello");s2=newString("hello");System.out.println(s1==s2);System.out.println(s1.equals(s2));}}28.求下列Strings="du*^JG";中大寫字母和小寫字母,和其他個(gè)字符各多少個(gè)?publicclassTestString2{publicstaticvoidmain(String[]args){Strings="du*^JG";StringlStr="abcdefghijklmnopqrstuvwxyz";StringuStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ";intlCount=0;intuCount=0;intoCount=0;for(inti=0;i<s.length();i++){charc=s.charAt(i);if(lStr.indexOf(c)!=-1){lCount++;}elseif(uStr.indexOf(c)!=-1){uCount++;}else{oCount++;}}System.out.print(lCount+""+uCount+""+oCount);}}29.求java這個(gè)字符串在下列字符串中出現(xiàn)的次數(shù)Strings="5454javaadsfjavaadfasfjavasdfajavaaadfjavaADFAjava545";publicclassTestString3{publicstaticvoidmain(String[]args){Strings="5454javaadsfjavaadfasfjavasdfajavaaadfjavaADFAjava545";intcount=0;while(s.indexOf("java")!=-1){s=s.substring(s.indexOf("java")+"java".length());count++;}System.out.println(count);}}30.將文件復(fù)制到新的位置importjava.io.*;publicclassFileCopy{publicstaticvoidmain(String[]args){intb=0;FileReaderin=null;FileWriterout=null;try{in=newFileReader("d:/share/java/HelloWorld.java");out=newFileWriter("d:/share/java/io/HW.java");while((b=in.read())!=-1){out.write(b);}out.close();in.close();}catch(FileNotFoundExceptione2){System.out.println("找不到指定文件");System.exit(-1);}catch(IOExceptione1){System.out.println("文件復(fù)制錯(cuò)誤");System.exit(-1);}System.out.println("文件已復(fù)制");}}31.緩沖區(qū)字節(jié)流舉例importjava.io.*;publicclassTestBufferStream1{publicstaticvoidmain(String[]args){try{FileInputStreamfis=newFileInputStream("E:/EclipseCode_MyEclipse/Chapter8/src/TestBufferStream1.java");BufferedInputStreambis=newBufferedInputStream(fis);intc=0;System.out.println(bis.read());System.out.println(bis.read());bis.mark(100);for(inti=0;i<=10&&(c=bis.read())!=-1;i++){System.out.print((char)c+"");}System.out.println();bis.reset();for(inti=0;i<=10&&(c=bis.read())!=-1;i++){System.out.print((char)c+"");}bis.close();}catch(IOExceptione){e.printStackTrace();}}}32.緩沖區(qū)字符流舉例importjava.io.*;publicclassTestBufferStream2{publicstaticvoidmain(String[]args){try{BufferedWriterbw=newBufferedWriter(newFileWriter("e:/Javacode/dat2.txt"));BufferedReaderbr=newBufferedReader(newFileReader("e:/Javacode/dat2.txt"));Strings=null;for(inti=1;i<=100;i++){s=String.valueOf(Math.random());bw.write(s);bw.newLine();}bw.flush();while((s=br.readLine())!=null){System.out.println(s);}bw.close();br.close();}catch(IOExceptione){e.printStackTrace();}}}33.?dāng)?shù)據(jù)流舉例importjava.io.*;publicclassTestDataStream{publicstaticvoidmain(String[]args){ByteArrayOutputStreambaos=newByteArrayOutputStream();//在內(nèi)存空間里分配一個(gè)字節(jié)數(shù)組DataOutputStreamdos=newDataOutputStream(baos);try{dos.writeDouble(Math.random());dos.writeBoolean(true);ByteArrayInputStreambais=newByteArrayInputStream(baos.toByteArray());System.out.println(bais.available());DataInputStreamdis=newDataInputStream(bais);System.out.println(dis.readDouble());System.out.println(dis.readBoolean());dos.close();dis.close();}catch(IOExceptione){e.printStackTrace();}}}34.字節(jié)流舉例importjava.io.*;publicclassTestFileInputStream{publicstaticvoidmain(String[]args){intb=0;FileInputStreamin=null;try{in=newFileInputStream("E:/EclipseCode_MyEclipse/Chapter8/src/TestFileInputStream.java");}catch(FileNotFoundExceptione){System.out.println("找不到指定文件");System.exit(-1);}try{longnum=0;while((b=in.read())!=-1){System.out.print((char)b);num++;}in.close();System.out.println();System.out.println("共讀取了"+num+"個(gè)字節(jié)");}catch(IOExceptione1){System.out.println("文件讀取錯(cuò)誤");System.exit(-1);}}}35.字節(jié)流舉例importjava.io.*;publicclassTestFileOutputStream{publicstaticvoidmain(String[]args){intb=0;FileInputStreamin=null;FileOutputStreamout=null;try{in=newFileInputStream("E:/EclipseCode_MyEclipse/Chapter8/src/TestFileOutputStream.java");out=newFileOutputStream("E:/Javacode/TestFileOutputStream.java");while((b=in.read())!=-1){out.write(b);}in.close();out.close();}catch(FileNotFoundExceptione2){System.out.println("找不到指定文件");System.exit(-1);}catch(IOExceptione1){System.out.println("文件復(fù)制錯(cuò)誤");System.exit(-1);}System.out.println("文件已復(fù)制");}}36.File字符舉例importjava.io.*;publicclassTestFileReader{publicstaticvoidmain(String[]args){FileReaderfr=null;intc=0;try{fr=newFileReader("E:/EclipseCode_MyEclipse/Chapter8/src/TestFileOutputStream.java");intln=0;while((c=fr.read())!=-1){//charch=(char)fr.read();System.out.print((char)c);//if(++ln>=100){System.out.println();ln=0;}}fr.close();}catch(FileNotFoundExceptione){System.out.println("找不到指定文件");}catch(IOExceptione){System.out.println("文件讀取錯(cuò)誤");}}}37.File字符流舉例importjava.io.*;publicclassTestFileWriter{publicstaticvoidmain(String[]args){FileWriterfw=null;try{fw=newFileWriter("e:/Javacode/unicode.dat");for(intc=0;c<=50000;c++){fw.write(c);}fw.close();}catch(IOExceptione1){e1.printStackTrace();System.out.println("文件寫入錯(cuò)誤");System.exit(-1);}}}importjava.io.*;publicclassTestFileWriter2{publicstaticvoidmain(String[]args)throwsException{FileReaderfr=newFileReader("d:/java/io/TestFileWriter2.java");FileWriterfw=newFileWriter("d:/java/io/TestFileWriter2.bak");intb;while((b=fr.read())!=-1){fw.write(b);}fr.close();fw.close();}}38.Object流舉例importjava.io.*;publicclassTestObjectIO{publicstaticvoidmain(Stringargs[])throwsException{Tt=newT();t.k=8;FileOutputStreamfos=newFileOutputStream("e:/Javacode/testobjectio.dat");ObjectOutputStreamoos=newObjectOutputStream(fos);oos.writeObject(t);oos.flush();oos.close();FileInputStreamfis=newFileInputStream("e:/Javacode/testobjectio.dat");ObjectInputStreamois=newObjectInputStream(fis);TtReaded=(T)ois.readObject();System.out.println(tReaded.i+""+tReaded.j+""+tReaded.d+""+tReaded.k);}}classTimplementsSerializable{inti=10;intj=9;doubled=2.3;transientintk=15;}39.打印流舉例importjava.io.*;publicclassTestPrintStream1{publicstaticvoidmain(String[]args){PrintStreamps=null;try{FileOutputStreamfos=newFileOutputStream("e:/Javacode/log.dat");ps=newPrintStream(fos);}catch(IOExceptione){e.printStackTrace();}if(ps!=null){System.setOut(ps);}intln=0;for(charc=0;c<=60000;c++){System.out.print(c+"");if(ln++>=100){System.out.println();ln=0;}}}}40.打印流舉例importjava.io.*;publicclassTestPrintStream2{publicstaticvoidmain(String[]args){Stringfilename=args[0];if(filename!=null){list(filename,System.out);}}publicstaticvoidlist(Stringf,PrintStreamfs){try{BufferedReaderbr=newBufferedReader(newFileReader(f));Strings=null;while((s=br.readLine())!=null){fs.println(s);}br.close();}catch(IOExceptione){fs.println("無(wú)法讀取文件");}}}41.打印流舉例importjava.util.*;importjava.io.*;publicclassTestPrintStream3{publicstaticvoidmain(String[]args){Strings=null;BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));try{FileWriterfw=newFileWriter("e:/Javacode/logfile.log",true);//Log4JPrintWriterlog=newPrintWriter(fw);while((s=br.readLine())!=null){if(s.equalsIgnoreCase("exit"))break;System.out.println(s.toUpperCase());log.println("-----");log.println(s.toUpperCase());log.flush();}log.println("==="+newDate()+"===");log.flush();log.close();}catch(IOExceptione){e.printStackTrace();}}}42.轉(zhuǎn)換流舉例importjava.io.*;publicclassTestTransForm1{publicstaticvoidmain(String[]args){try{OutputStreamWriterosw=newOutputStreamWriter(newFileOutputStream("e:/Javacode/char.txt"));osw.write("mircosoftibmsunapplehp");System.out.println(osw.getEncoding());osw.close();osw=newOutputStreamWriter(newFileOutputStream("e:/Javacode/char.txt",true),"ISO8859_1");//latin-1osw.write("mircosoftibmsunapplehp");System.out.println(osw.getEncoding());osw.close();}catch(IOExceptione){e.printStackTrace();}}}43.轉(zhuǎn)化流舉例importjava.io.*;publicclassTestTransForm2{publicstaticvoidmain(Stringargs[]){InputStreamReaderisr=newInputStreamReader(System.in);BufferedReaderbr=newBufferedReader(isr);Strings=null;try{s=br.readLine();while(s!=null){if(s.equalsIgnoreCase("exit"))break;System.out.println(s.toUpperCase());s=br.readLine();}br.close();}catch(IOExceptione){e.printStackTrace();}}}//阻塞44.生產(chǎn)者消費(fèi)者模擬publicclassProducerConsumer{publicstaticvoidmain(String[]args){SyncStackss=newSyncStack();Producerp=newProducer(ss);Consumerc=newConsumer(ss);newThread(p).start();newThread(c).start();}}classWoTou{intid;WoTou(intid){this.id=id;}publicStringtoString(){return"WoTou:"+id;}}classSyncStack{intindex=0;WoTou[]arrWT=newWoTou[6];publicsynchronizedvoidpush(WoTouwt){while(index==arrWT.length){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}this.notifyAll();arrWT[index]=wt;index++;}publicsynchronizedWoToupop(){while(index==0){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}this.notifyAll();index--;returnarrWT[index];}}classProducerimplementsRunnable{SyncStackss=null;Producer(SyncStackss){this.ss=ss;}publicvoidrun(){for(inti=0;i<20;i++){WoTouwt=newWoTou(i);ss.push(wt);System.out.println("生產(chǎn)了:"+wt);try{Thread.sleep((int)(Math.random()*200));}catch(InterruptedExceptione){e.printStackTrace();}}}}classConsumerimplementsRunnable{SyncStackss=null;Consumer(SyncStackss){this.ss=ss;}publicvoidrun(){for(inti=0;i<20;i++){WoTouwt=ss.pop();System.out.println("消費(fèi)了:"+wt);try{Thread.sleep((int)(Math.random()*1000));}catch(InterruptedExceptione){e.printStackTrace();}}}}45.用代碼模擬死鎖問題publicclassTestDeadLockimplementsRunnable{publicintflag=1;staticObjecto1=newObject(),o2=newObject();publicvoidrun(){System.out.println("flag="+flag);if(flag==1){synchronized(o1){try{Thread.sleep(500);}catch(InterruptedExceptione){e.printStackTrace();}synchronized(o2){System.out.println("o2");}}}if(flag==0){synchronized(o2){try{Thread.sleep(500);}catch(InterruptedExceptione){e.printStackTrace();}synchronized(o1){System.out.println("o1");}}}}publicstaticvoidmain(String[]args){TestDeadLocktd1=newTestDeadLock();TestDeadLocktd2=newTestDeadLock();td1.flag=1;td2.flag=0;newThread(td1).start();newThread(td2).start();}}46.線程中斷舉例importjava.util.*;publicclassTestInterrupt{publicstaticvoidmain(String[]args){MyThreadthread=newMyThread(Thread.currentThread());thread.start();try{Thread.sleep(5000);
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 職業(yè)培訓(xùn)空調(diào)使用指南
- 汽車行業(yè)法律顧問聘用合同
- 旅游景區(qū)開發(fā)招投標(biāo)合同安排
- 家具設(shè)計(jì)履約評(píng)價(jià)管理辦法
- 旅游度假村HSE協(xié)議書
- 地鐵建設(shè)爆破作業(yè)合同樣本
- 北京市飛機(jī)交易合同
- 環(huán)境保護(hù)設(shè)施采購(gòu)流程
- 臨時(shí)城市規(guī)劃師合同范本
- 軟件采購(gòu)及合同履行要點(diǎn)
- 通識(shí)類(200道)乙級(jí)考試題庫(kù)
- 劍橋?qū)W習(xí)科學(xué)手冊(cè)-方法論課件
- 【蒙牛集團(tuán)財(cái)務(wù)共享業(yè)財(cái)融合實(shí)施的案例探析9000字(論文)】
- 下肢動(dòng)脈閉塞的護(hù)理
- 2024年現(xiàn)代農(nóng)業(yè)技術(shù)的推廣和應(yīng)用
- 公司油卡管理制度
- 異常檢測(cè)方法
- 整體租賃底商運(yùn)營(yíng)方案(技術(shù)方案)
- 瓣周漏護(hù)理查房
- 建筑環(huán)境學(xué)第四版思考題答案
- 卓越績(jī)效管理模式之以顧客和市場(chǎng)為中心
評(píng)論
0/150
提交評(píng)論