public
class
MulileDownLoader {
public
static
final
String
path
=
"http://192.168.1.8:8080/code/aiqiyi.exe"
;
private
static
int
threadcount
=3;
private
static
int
blocksize
=0;
private
static
int
livingthread
=0;
/**
* 多线程下载
*
@param
args
*/
public
static
void
main(String[] args)
throws
Exception{
//创建并设置url
URL url=
new
URL(
path
);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(
"GET"
);
conn.setConnectTimeout(3000);
//获取服务器内容的长度
int
length = conn.getContentLength();
System.
out
.println(
"服务器文件长度:"
+length);
//创建一个和服务器文件大小相同的本地文件
RandomAccessFile raf=
new
RandomAccessFile(
"aiqiyi.exe"
,
"rw"
);
raf.setLength(length);
//计算每个线程下载的位置
blocksize
=length/
threadcount
;
System.
out
.println(
"每个线程下载的平均长度:"
+
blocksize
);
livingthread
=
threadcount
;
for
(
int
i=1;i<=
threadcount
;i++){
int
startIndex=(i-1)*
blocksize
;
int
endIndex=i*
blocksize
-1;
if
(i==
threadcount
){
endIndex=length;
}
new
Thread(
new
DownLoadTask(i, startIndex, endIndex)).start();
}
}
/**
* 线程下载文件
*
@author
Administrator
*
*/
public
static
class
DownLoadTask
implements
Runnable {
private
int
id
;
private
int
startIndex
;
private
int
endIndex
;
public
DownLoadTask(
int
id,
int
startIndex,
int
endIndex) {
super
();
this
.
id
= id;
this
.
startIndex
= startIndex;
this
.
endIndex
= endIndex;
}
public
void
run() {
try
{
//创建url 并设置url
URL url=
new
URL(
path
);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod(
"GET"
);
conn.setConnectTimeout(3000);
//创建一个和服务器文件大小相同的本地文件
RandomAccessFile raf=
new
RandomAccessFile(
"aiqiyi.exe"
,
"rw"
);
//设置下载文件范围
conn.setRequestProperty(
"Range"
,
"bytes="
+
startIndex
+
"-"
+
endIndex
);
//服务器端返回的输入流
InputStream is = conn.getInputStream();
raf.seek(
startIndex
);
//定位写文件开始的位置
int
len=0;
byte
[] buf=
new
byte
[1024];
while
((len=is.read(buf))!=-1){
raf.write(buf, 0, len);
}
raf.close();
is.close();
System.
out
.println(
"线程:"
+
id
+
"下载完毕...."
);
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
synchronized
(MulileDownLoader.
class
) {
threadcount
--;
if
(
threadcount
<=0){
System.
out
.println(
"全部下载完毕......"
);
}
}
}
}
}
}