多线程下载

多线程下载的原理:

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();
}

}
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值