java 多线程下载文件并实时计算下载百分比(断点续传)

时间:2023-03-08 21:46:22

多线程下载文件

多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来即可。

涉及的知识及问题

  • 请求的数据怎么拆分
  • 拆分完成后怎么下载
  • 如何计算实时下载量

一.请求的数据怎么拆分

 int blockSize =fileLength/threadCount; //计算每个线程需要下的长度
for(int i=0;i<threadCount;i++) {
int startSize=i*blockSize; //当前线程需要下载的开始位置
int endSize=(i+1)*blockSize-1;//当前线程需要下载的结束位置
if(1+i==threadCount) { //最后一个线程的结尾赋值文件大小
endSize=fileLength;
}
threadList[i]= new DownThread_1(filePath, fileUrl, "线程"+i, startSize, endSize);
threadList[i].start();
}

二.拆分完成后怎么下载

try {
URL url = new URL(urlPath);
HttpURLConnection coon = (HttpURLConnection) url.openConnection();
coon.setRequestProperty("range","bytes="+startSize+"-"+endSize); //设置获取下载资源的开始位置和结束位置
coon.setConnectTimeout(5000);
if(coon.getResponseCode()==206) {//响应码 因为上面设置了range 所有响应码是206不再是200
BufferedInputStream bi=new BufferedInputStream(coon.getInputStream());
RandomAccessFile raf=new RandomAccessFile(filePath, "rwd"); //断点续传的关键
raf.seek(startSize); //将写入点移动到当前线程写入开始位置
byte b[]=new byte[1024];
int len=0;
while ((len=bi.read(b))>-1) { //循环写入
raf.write(b, 0, len);
synchronized (DownUtile.class) {//此处涉及到变量同步
DownUtile.downLength=DownUtile.downLength+len; //计算当前下载了多少
}
}
raf.close();
bi.close();
System.out.println("thread"+threadName+"下载完成,开始位置"+startSize+",结束位置"+endSize);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

三.如何计算实时下载量

    while ((len=bi.read(b))>-1) { //循环写入
raf.write(b, 0, len);
synchronized (DownUtile.class) {//此处涉及到变量同步
DownUtile.downLength=DownUtile.downLength+len; //计算当前下载了多少
}
} while(DownUtile.downOver) {
Thread.sleep(500); //间隔0.5秒计算一下
if(DownUtile.downLength==fileLength) {
DownUtile.downOver=false;
System.out.println("下载完成:100%");
}else {
System.out.println("已经下载了:"+((int) (float)DownUtile.downLength / (float) fileLength * 100)+"%");
}
}

上述方法中  用到了synchronized(类锁),为什么用到类锁,因为计算下载的参数在DownUtile类中,为了保证这个参数在多线程中同步,需保证在执行累加操作时线程安全。

下面贴上全部的代码

 public class DownLoadUtile {
public static String filePath="C:\\Users\\Administrator\\Desktop\\下载\\ deme.exe"; //文件保存地址
public static String fileUrl="http://123.6.39.120/dlied1.qq.com/lol/dltools/LOL_V4.1.2.3-V4.1.2.4_PATCH_0_tgod_signed.exe?mkey=5cfc8d87dddd9a57&f=5844&cip=221.221.188.162&proto=http";//文件地址
public static int threadCount=5; //线程数量
public static int fileLength=0; //文件大小
public static Thread [] threadList=new Thread[threadCount]; public DownLoadUtile() { }
public DownLoadUtile(int threadCount) {//有参构造
this.threadCount=threadCount;
} public static void main(String[] args) throws Exception {
URL url=new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //创建连接对象
conn.setConnectTimeout(5000);//请求超时时间 int code = conn.getResponseCode();
System.out.println("服务器响应码"+code);
if(code==200) {//响应正常
fileLength=conn.getContentLength(); //获取文件大小
File file = new File(filePath);
if(!file.exists()) {
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(filePath, "rwd"); //断点续传的关键
raf.setLength(fileLength); int blockSize =fileLength/threadCount; //计算每个线程需要下的长度
for(int i=0;i<threadCount;i++) {
int startSize=i*blockSize; //当前线程需要下载的开始位置
int endSize=(i+1)*blockSize-1;//当前线程需要下载的结束位置
if(1+i==threadCount) { //最后一个线程的结尾赋值文件大小
endSize=fileLength;
}
threadList[i]= new DownThread_1(filePath, fileUrl, "线程"+i, startSize, endSize);
threadList[i].start();
} while(DownUtile.downOver) {
Thread.sleep(500); //间隔0.5秒计算一下
if(DownUtile.downLength==fileLength) {
DownUtile.downOver=false;
System.out.println("下载完成:100%");
}else {
System.out.println("已经下载了:"+((int) (float)DownUtile.downLength / (float) fileLength * 100)+"%");
}
} }else {
System.out.println("服务器响应失败"+code);
} }

下载类

 public class DownThread_1 extends Thread{

     private String filePath;
private String urlPath;
private String threadName;
private int startSize;
private int endSize; public DownThread_1(String filePath,String urlPath,String threadName,int startSize,int endSize) {
this.endSize=endSize;
this.startSize=startSize;
this.filePath=filePath;
this.urlPath=urlPath;
this.threadName=threadName;
}
@Override
public void run() {
try {
URL url = new URL(urlPath);
HttpURLConnection coon = (HttpURLConnection) url.openConnection();
coon.setRequestProperty("range","bytes="+startSize+"-"+endSize); //设置获取下载资源的开始位置和结束位置
coon.setConnectTimeout(5000);
if(coon.getResponseCode()==206) {//响应码 因为上面设置了range 所有响应码是206不再是200
BufferedInputStream bi=new BufferedInputStream(coon.getInputStream());
RandomAccessFile raf=new RandomAccessFile(filePath, "rwd"); //断点续传的关键
raf.seek(startSize); //将写入点移动到当前线程写入开始位置
byte b[]=new byte[1024];
int len=0;
while ((len=bi.read(b))>-1) { //循环写入
raf.write(b, 0, len);
synchronized (DownUtile.class) {//此处涉及到变量同步
DownUtile.downLength=DownUtile.downLength+len; //计算当前下载了多少
}
}
raf.close();
bi.close();
System.out.println("thread"+threadName+"下载完成,开始位置"+startSize+",结束位置"+endSize);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }

参数类

 public class DownUtile {

     public static  int downLength=0;//已经下载了多少

     public static boolean downOver=true; //下载是否完成

 }