package downLoad;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MultiThreadDownLoader {
// 2、使用的子线程的个数
private static int threadCount = 3;
/**
* @param args
*/
public static void main(String[] args) {
try {
String path = "https://download.jetbrains.8686c.com/idea/ideaIU-2018.3.1.exe";//文件路径
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int code = conn.getResponseCode();
if (code == 200) {
int length = conn.getContentLength();
// 1、在客户端创建一个与服务端文件一样大小的文件
RandomAccessFile file = new RandomAccessFile("temp.exe", "rw");
file.setLength(length);
// 3、每个子线程下载数据块 ,下载的起始位置和结束位置
int blockSize = length / threadCount;
// threadId * blockSize ---- (threadId+1)* blockSize -1
for (int threadId = 0; threadId < threadCount; threadId++) {
// 下载的起始位置和结束位置
int startIndex = threadId * blockSize;
int endIndex = 0;
if (threadId != (threadCount - 1)) {
endIndex = (threadId + 1) * blockSize - 1;
} else {
endIndex = length - 1;
}
// 开启子线程下载数据
new ThreadDownLoader(path, startIndex, endIndex, threadId, threadCount).start();
}
} else {
// 抛出异常
}
} catch (Exception e) {
e.printStackTrace();
}
}
}