多线程下载的原理:
1、获取服务器上目标资源的大小
2、确定开启几条线程下载
3、用目标资源总大小除以线程个数,得出每条线程需要下载的大小
4、算出每个线程的开始位置和结束位置
5、开启多线程下载
代码实现如下:
package com.heima.morethread;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MultiDownload {
private static String path = "http://192.168.0.107:8080/feiqiu.exe";
private static int threadCount = 3;
private static int length;
public static void main(String[] args) throws Exception{
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
int code = con.getResponseCode();
if(code == 200){
//获取服务器文件的大小
length = con.getContentLength();
System.out.println(length);
int blockSize = length / threadCount;
for (int i = 0; i < threadCount; i++) {
int startIndex = i * blockSize;
int endIndex = (i + 1) * blockSize - 1;
if(i == threadCount - 1){
endIndex = length - 1;
}
System.out.println("线程id:" + i + "下载位置:" + startIndex + "--" + endIndex);
DownLoadThread loadThread = new DownLoadThread(path, startIndex, endIndex, i);
loadThread.start();
}
}
//在当前项目下创建一个文件,大小和服务器文件大小一样
//RandomAccessFile raf = new RandomAccessFile("temp.exe", "rw");
//raf.setLength(length);
}
public static class DownLoadThread extends Thread{
private String path;
private int startIndex;
private int endIndex;
private int threadId;
public DownLoadThread(String path,int startIndex,int endIndex,int threadId){
this.path = path;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
public void run() {
try {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
int code = con.getResponseCode();
if(code == 200){
InputStream in = con.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");
//设置文件写入的初始位置
raf.seek(startIndex);
int len = -1;
byte[] buffer = new byte[1024];
while((len = in.read(buffer)) != -1){
raf.write(buffer, 0, len);
}
raf.close();
System.out.println("线程id:" + threadId + "下载完毕了");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}