Main class:
1 Public classDownthreaddemo {2 3 Public Static voidMain (string[] args) {4 //TODO auto-generated Method Stub5 intThreadnum = 3;6 LongFileLen = 0;7 LongNumperthread = 0;8 Longleft = 0;9URL url =NULL;TenURLConnection connection =NULL; OneString fileName = "E:\\temp\\downlo.jpg"; ARandomaccessfile[] RAF =NewRandomaccessfile[threadnum]; -Inputstream[] is =NewInputstream[threadnum]; - Try { theURL =NewURL ( -"Http://img.bizhi.sogou.com/images/2014/08/22/830201.jpg"); - //Open Network Connection -Connection =url.openconnection (); + //Calculate File Size -FileLen =Connection.getcontentlengthlong (); + //file sizes processed per thread ANumperthread = FileLen/threadnum; at //last piece -left = fileLen%threadnum; - //openconnection (). getInputStream () -Is[0] =Url.openstream (); -Raf[0] =NewRandomaccessfile (FileName, "RW"); -Raf[0].setlength (fileLen); in //Create a stream that reads from the network and writes to the file for each thread, respectively. - for(inti = 0; i < threadnum; i++) { to if(I! = 0) { +Is[i] =Url.openstream (); -Raf[i] =NewRandomaccessfile (FileName, "RW"); the } * if(i = = ThreadNum-1) { $ NewMultydown (i * numperthread, (i + 1) *NumperthreadPanax Notoginseng+Left , Is[i], Raf[i]). Start (); -}Else { the NewMultydown (i * numperthread, (i + 1) *Numperthread, + Is[i], Raf[i]). Start (); A } the } +}Catch(malformedurlexception e) { - //TODO auto-generated Catch block $ e.printstacktrace (); $}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); the } -SYSTEM.OUT.PRINTLN ("End------");Wuyi } the -}
Thread class:
1 Public classMultydownextendsThread {2 Private Longstart, end;3 PrivateInputStream is;4 PrivateRandomaccessfile RAF;5 6 PublicMultydown () {7 //TODO auto-generated Constructor stub8 }9 Ten PublicMultydown (LongStartLongend, InputStream is, Randomaccessfile RAF) { One //TODO auto-generated Constructor stub A This. Start =start; - This. end =end; - This. is =is ; the This. RAF =RAF; - } - - @Override + Public voidrun () { - //TODO auto-generated Method Stub + A intLen = 0; at intSize = 0; - byte[] B =New byte[24]; - Try { - //jump to file specified location - Is.skip (start); - Raf.seek (start); in while(len = Is.read (b))! =-1 && size < (end-start)) { -Raf.write (b, 0, Len); toSize + =Len; + } -}Catch(IOException e) { the //TODO auto-generated Catch block * e.printstacktrace (); $}finally {Panax Notoginseng if(Is! =NULL) { - Try { the is.close (); +}Catch(IOException e) { A //TODO auto-generated Catch block the e.printstacktrace (); + } - } $ if(RAF! =NULL) { $ Try { - raf.close (); -}Catch(IOException e) { the //TODO auto-generated Catch block - e.printstacktrace ();Wuyi } the } - } Wu } - About}
Multithreading download files from the network