Annegu a simple HTTP multithreaded download program to discuss multithreading concurrent downloads and breakpoint continuation issues.
The function of this program is that the data can be downloaded from the destination address by multiple threads, each thread is responsible for downloading a part, and can support the continuation of the breakpoint and the timeout connection.
The download method is download (), which receives two parameters, namely the URL and encoding of the page to be downloaded. In this download-responsible approach, there are three main steps. The first step is to set a breakpoint to continue the time of some information, the second step is the main thread of the download, and finally the data merge.
1, Multithreading Download:
/** *//** http://www.bt285.cn http://www.5a520.cn
*/
public string Download (string urlstr, String charset) {
This.charset = CharSet;
long contentlength = 0;
Countdownlatch latch = new Countdownlatch (threadnum);
long[] startpos = new Long[threadnum];
long endpos = 0;
try {
//From the URL to obtain the downloaded file format and name
this.filename = urlstr.substring (Urlstr.lastindexof ("/") + 1);
this.url = new URL (urlstr);
urlconnection con = url.openconnection ();
SetHeader (con);
//Get the length of the content
contentlength = Con.getcontentlength ();
//The context is divided into threadnum segments, the length of each paragraph.
this.threadlength = Contentlength/threadnum;
//First, analyze the temporary files that have been downloaded, set breakpoints, and create the destination file if it is a new download task. Explained in the 4th.
startpos = Setthreadbreakpoint (Filedir, FileName, ContentLength, startpos);
//Step two, download files in multiple threads
Executorservice exec = Executors.newcachedthreadpool ();
for (int i = 0; i < threadnum; i++) {
//Create a thread to download the data, the starting position for each piece of data (threadlength * i + downloaded length)
Startpos[i] + = threadlength * I;
/**//* Sets the ending position of the child thread, not the last thread (Threadlength * (i + 1)-1)
the end of the last thread is the length of the download content * *
if (i = = threadNum-1) {
endpos = contentlength;
} else {
Endpos = Threadlength * (i + 1)-1;
}
//Open the child thread and execute.
childthread thread = new Childthread (this, latch, I, startpos[i], endpos);
childthreads[i] = thread;
Exec.execute (thread);
}
try {
The
//wait Countdownlatch signal is 0, indicating that all child threads have ended.
latch.await ();
Exec.shutdown ();
//Step three, write the contents of the temporary file downloaded from the section to the target file. Explained in the 3rd.
Tempfiletotargetfile (childthreads);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}