- 单线程,实现具体任务
package com.hongfu.spring.Thread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class SingleThreadFileDownload implements Runnable{
private String urlDown;
private String filePath;
private long start;
private long end;
public SingleThreadFileDownload(String urlDown, String filePath, long start, long end) {
this.urlDown = urlDown;
this.filePath = filePath;
this.start = start;
this.end = end;
}
@Override
public void run() {
InputStream is = null;
RandomAccessFile out = null;
try {
URL url = new URL(urlDown);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
File file = new File(filePath);
out = null;
if (file != null) {
out = new RandomAccessFile(file, "rw");
}
out.seek(start);
is = conn.getInputStream();
byte[] bytes = new byte[1024];
int l = 0;
while ((l = is.read(bytes))!=-1){
out.write(bytes,0,l);
}
System.out.println(Thread.currentThread().getName()+"完成下载!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 创建单线程,实现多线程下载
package com.hongfu.spring.Thread;
import java.net.URL;
import java.net.URLConnection;
public class moreThreadDownFile {
public static void main(String[] args) {
try {
getFileWithThreadPool("https://issuecdn.baidupcs.com/issue/netdisk/yunguanjia/BaiduNetdisk_7.8.5.1.exe","D:\\百度.exe",5);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getFileWithThreadPool(String urlLocation, String filePath, int poolLength) throws Exception{
long start = 0;
int length = 0;
URL url = null;
url = new URL(urlLocation);
URLConnection urlConnection = url.openConnection();
length = urlConnection.getContentLength();
System.out.println(length);
for (int i = 0; i < poolLength; i++) {
start = i * length / poolLength;
long end = (i + 1) * length / poolLength - 1;
System.out.println(start+"---------------"+end);
Thread thread = new Thread(new SingleThreadFileDownload(urlLocation, filePath, start, end));
thread.setName("线程"+(i+1));
thread.start();
}
}
}
- 测试结果如图
![在这里插入图片描述](https://img-blog.csdnimg.cn/51e6ed8b89da47e3b2a4537e108a2ac8.png)