php thread类下载,多线程下载一个文件

学习了多线程下载文件

public class DownLoad2 {

/**

* 多线程下载

* */

private static long startTimeMillis = 0; // 开始时间

private long endTimeMillis = 0; // 结束时间

public void down() {

startTimeMillis = System.currentTimeMillis(); // 记录方法开始执行的时间

String url = "http://cyar.118320.com/imports/uploadFile/2016-07-011.xlsx";

HttpClient client = new HttpClient();

GetMethod method = new GetMethod(url);

URL url2=null;

try {

url2 = new URL(url);

} catch (MalformedURLException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

try {

client.executeMethod(method);

int length=Integer.valueOf(method.getResponseContentLength()+"");

RandomAccessFile file = new RandomAccessFile("C:/Users/Administrator/Desktop/工作/b.xlsx","rw");//创建一个相同大小的文件。

//7:设置文件大小,占位

file.setLength(length);//设置文件大小。

file.close();

//8:定义线程个数

int size = 3;

//9:计算每一个线程应该下载多少字节的数据,如果正好整除则最好,否则加1

int block = length/size==0?length/size:length/size+1;//计算每个线程应该下载的数据量。

System.err.println("每个线程应该下载:"+block);

for(int i=0;i

int start = i*block;

int end = start+(block-1);//计算每一个线程的开始和结束字节。

System.err.println(i+"="+start+","+end);

new MyDownThread(start, end,url2).start();

}

} catch (HttpException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

endTimeMillis = System.currentTimeMillis(); // 记录方法执行完成的时间

System.out.println("执行时间:" + (endTimeMillis - startTimeMillis) + "ms;");

}

class MyDownThread extends Thread{

//定义从何地开始下载

private int start;

//定义下载到哪一个字节

private int end;

private URL url;

public MyDownThread(int start,int end,URL url){

this.start=start;

this.end=end;

this.url=url;

}

@Override

public void run() {

try{

//11:开始下载

HttpURLConnection con =

(HttpURLConnection) url.openConnection();

con.setRequestMethod("GET");

//12:设置分段下载的请求头

con.setRequestProperty("Range","bytes="+start+"-"+end);//设置从服务器上读取的文件块。

//13:开始下载,需要判断206

if(con.getResponseCode()==206){//访问成功,则返回的状态码为206。

InputStream in = con.getInputStream();

//14:声明随机写文件对象,注意rwd是指即时将数据写到文件中,而不使用缓存区

RandomAccessFile out = new RandomAccessFile("C:/Users/Administrator/Desktop/工作/b.xlsx","rwd");

out.seek(start);//设置从文件的某个位置开始写数据。

byte[] b=new byte[1024];

int len = 0;

while((len=in.read(b))!=-1){

out.write(b,0,len);

}

out.close();

in.close();

}

System.err.println(this.getName()+"执行完成");

}catch(Exception e){

throw new RuntimeException(e);

}

}

}

public static void main(String[] args) {

DownLoad2 down=new DownLoad2();

down.down();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值