作者的個人分享網:分享時刻【www.itison.cn】
java多線程下載示例
多線程下載,如果想要做測試,必須要修改相應的文件路徑,打開服務器纔可,否則會出現異常。
代碼如下:
/**多線程下載**/
package com.demo;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
class DownloadThread extends Thread {
int start;
int end;
String path;
public DownloadThread(int start, int end, String path) {
this.start = start;
this.end = end;
this.path = path;
}
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
InputStream is = conn.getInputStream();
System.out.println(Thread.currentThread().getName() + "號線程負責的下載範圍:" + start + "---" + end);
RandomAccessFile raf = new RandomAccessFile("c:\\aaa\\test.exe", "rw");
raf.seek(start);
byte[] b = new byte[1024];
int nRead = 0;
while((nRead = is.read(b)) != -1) {
raf.write(b, 0, nRead);
}
System.out.println(Thread.currentThread().getName() + "號線程下載完畢!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MulThreadDownload {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String path = "http://localhost:8080/MyWebServer/qqpcmgr.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int length = conn.getContentLength();
System.out.println("資源總長度:" + length);
RandomAccessFile raf = new RandomAccessFile("c:\\aaa\\test.exe", "rw");
raf.setLength(length);
int blockCount = 3; //總的線程數量
int blockSize = length / blockCount; //每個線性要下載的數據量
for (int i = 1; i <= blockCount; i++) {
int start = (i - 1) * blockSize;
int end = i * blockSize - 1;
if (i == blockCount) {
end = length - 1;
}
new DownloadThread(start, end, path).start();
}
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}