public class Multidownloader {
private static int ThreadCount = 3;
public static void main(String[] args) throws Exception {
String path = "http://192.168.0.100/Server/e.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式
conn.setRequestMethod("GET");
//设置超时时间
conn.setConnectTimeout(5000);
//得到响应码
int code = conn.getResponseCode();
if(code == 200) {
//获取要下载文件的总大小
int length = conn.getContentLength();
//创建一个要和下载文件一样大的文件
RandomAccessFile raf = new RandomAccessFile("temp.exe", "rwd");
raf.setLength(length);
raf.close();
//计算每个线程下载多少
//使用总大小除以线程个数
int blockSize = length / ThreadCount;
//计算每个线程的起始索引并开始下载
for (int threadId = 0; threadId < ThreadCount; threadId++) {
//计算起始索引
int startIndex = threadId * blockSize;
//计算结束索引
int endIndex = (threadId + 1) * blockSize - 1;
//最后一个线程,结束索引应该到文件结尾
if(threadId == ThreadCount - 1) {
endIndex = length - 1;
}
new DownLoaderThread(threadId, startIndex, endIndex).start();
}
}
}
public static class DownLoaderThread extends Thread {
private int threadId;
private int startIndex;
private int endIndex;
public DownLoaderThread(int threadId,int startIndex,int endIndex) {
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@Override
public void run() {
try {
System.out.println("线程" + threadId + "起始索引:" + startIndex);
System.out.println("线程" + threadId + "结束索引:" + endIndex);
String path = "http://192.168.0.100/Server/e.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
//设置请求头
// range bytes=0-100 请求前100个字节
//请求一部分资源
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
int code = conn.getResponseCode();
//部分响应成功
if(code == 206) {
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe", "rwd");
//设置从那个索引(位置)写入文件
raf.seek(startIndex);
int len = 0;
byte[] bys = new byte[1024];
while((len = is.read(bys)) != -1) {
raf.write(bys,0,len);
}
raf.close();
is.close();
System.out.println("线程" + threadId + "下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
多线程下载的原理
最新推荐文章于 2018-11-23 06:22:40 发布