多线程下载
下载线程类
//多线程下载首先要有一个开始,一个结束和线程的id
private long startTime;
private long endTime;
private int id;
//直接构造出有参的构造函数
public Download(long startTime, long endTime, int id) {
super();
this.startTime = startTime;
this.endTime = endTime;
this.id = id;
}
run方法
由于是多线程,处于线程的行列,所以需要继承Thread 或实现Runnable。
这里以Runnable为例子。
long start = System.currentTimeMillis();
try {
URL url = new URL(Download2.path);
URLConnection urlConnection = (HttpURLConnection) url.openConnection();
//setRequestMethod("xxx"),xxx可以为POST和GET 映射时没有使用该标识,POST和GET请求都可以处理
((HttpURLConnection) urlConnection).setRequestMethod("GET");
//setConnectTimeout(time)从主机连接最大时间,超出最大时间,判定为超时 time为毫秒 1000毫秒=1秒
urlConnection.setConnectTimeout(10000);
//setReadTimeout(time)从主机读取最大时间,超出最大时间,判定为超时
urlConnection.setReadTimeout(10000);
urlConnection.addRequestProperty("Range","bytes="+startTime+"-"+endTime);
if(((HttpURLConnection) urlConnection).getResponseCode()==206) {
//取出连接中的数据
InputStream is = urlConnection.getInputStream();
//本地接收文件的位置,及其接收后文件的名字
File file = new File("D:\\1.exe");
//输出流,开始写数据,随机读写流
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(start);//跳转到线程开始的位置
System.out.println("线程"+id+" 开始的位置:"+startTime+"\t"+" 结束位置"+endTime);
//字节流传输数据,每次传输8192kb
byte [] buf= new byte[8192];
int len=0;
while((len=is.read(buf))!=-1) {
raf.write(buf, 0, len);
}
raf.close();
is.close();
//每个线程完成下载以后,完成下载的线程数+1
Download2.success++;
//线程下载数量和总线程数量一致时,完成下载线程数量变成0
synchronized (Download2.path) {
System.out.print("线程"+id+"下载完毕");
if(Download2.success==Download2.success) {
Download2.success=0;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
long end =System.currentTimeMillis();
System.out.println("\t运行时间"+(end - start));
下载测试类
//下载测试类,首先要有一个下载测试的连接,线程的数量,还有一个承接线程类完成数量的变量
static String path = "http://download2.m3guo.com/MSangoSetup1.2.22.51.exe";
static int number=6;//线程数
static int success=0;//和线程数有关,记录线程完成的个数
main方法
long start =System.currentTimeMillis();
//统一资源管理器,可以直接打开网络地址
URL url = new URL(Download2.path);
//因为是基于Http请求,获取httpUrlConnection,获取网络连接对象,和服务器建立联系
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置参数
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);//连接超时
httpURLConnection.setReadTimeout(5000);//读取超时
if(httpURLConnection.getResponseCode()==200) {
//获取文件总长度
int count = httpURLConnection.getContentLength();
//每个线程下载的大小
int size = count/number;
//开启线程进行下载
for (int i = 0; i < number; i++) {
long startIndex = size * i;
long endIndex = size * (i + 1);
Download download = new Download(startIndex, endIndex, i);
将runnable转化为thread 方便使用start方法
Thread thread = new Thread(download);
thread.start();
}
}
long end =System.currentTimeMillis();
System.out.println(end-start);