Java multi-thread download implementation, java multi-thread implementation

Source: Internet
Author: User

Java multi-thread download implementation, java multi-thread implementation

Copy codeThe Code is as follows:

Package cn. me. test;

Import java. io. InputStream;

Import java. io. RandomAccessFile;

Import java.net. HttpURLConnection;

Import java.net. URL;

/**

* Multi-thread download

* 1: Use RandomAccessFile to write data anywhere.

* 2: calculate the volume of data downloaded in the first thread, which can be evenly allocated. If the average is not enough,

* The last thread processes a relatively small amount of data.

* 3: files of the same size must be prepared and obtained through the file header before downloading.

*/

Public class MultiThreadDownload {

Public static void main (String [] args) throws Exception {

// 1: declare the file name and download address

String fileName = "aa.rar ";

String urlStr = "http: // localhost: 7777/day18 ";

// 2: declare the Url

URL url = new URL (urlStr + "/" + fileName );

// 3: Get the connection

HttpURLConnection con =

(HttpURLConnection) url. openConnection ();

// 4: SET THE REQUEST METHOD

Con. setRequestMethod ("GET ");

// 5: Get the request header, that is, the object Length

Int length = con. getContentLength (); // obtain the length of the downloaded file to calculate the amount of data that each thread should download.

// 6: create a file of the same size in the specified directory

RandomAccessFile file = new RandomAccessFile ("d:/a/" + fileName, "rw"); // create a file of the same size.

// 7: Set the file size and placeholder

File. setLength (length); // sets the file size.

 

File. close ();

// 8: defines the number of threads

Int size = 3;

// 9: calculate the number of bytes of data to be downloaded by each thread. It is best to divide the data exactly; otherwise, add 1.

Int block = length/size = 0? Length/size: length/size + 1; // calculate the data volume that each thread should download.


System. err. println ("Each thread should download:" + block );

// 10: run the three threads and calculate the start byte and end of the byte.

For (int I = 0; I <size; I ++ ){

Int start = I * block;

Int end = start + (block-1); // calculates the start and end bytes of each thread.

 

System. err. println (I + "=" + start + "," + end );

New MyDownThread (fileName, start, end, url). start ();

}

}

Static class MyDownThread extends Thread {

// Define the file name

Private String fileName;

// Define where to download

Private int start;

// Define which byte to download

Private int end;

Private URL;

Public MyDownThread (String fileName, int start, int end, URL url ){

This. fileName = fileName;

This. start = start;

This. end = end;

This. url = url;

}

@ Override

Public void run (){

Try {

// 11: Start download

HttpURLConnection con =

(HttpURLConnection) url. openConnection ();

Con. setRequestMethod ("GET ");

// 12: Set the multipart download request header.

Con. setRequestProperty ("Range", "bytes =" + start + "-" + end); // sets the file block read from the server.

 

// 13: start downloading. You need to determine the value 206.

If (con. getResponseCode () = 206) {// if the access is successful, status code 206 is returned.

InputStream in = con. getInputStream ();

// 14: declare random write object. Note that rwd refers to writing data to the file in real time without using the cache area.

RandomAccessFile out = new RandomAccessFile ("d:/a/" + fileName, "rwd ");

Out. seek (start); // set to write data from a certain position in the file.

Byte [] B = new byte [1024];

Int len = 0;

While (len = in. read (B ))! =-1 ){

Out. write (B, 0, len );

}

Out. close ();

In. close ();

}

System. err. println (this. getName () + "execution completed ");

} Catch (Exception e ){

Throw new RuntimeException (e );

}

}

}

}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.