日期:2014-05-20 浏览次数:20688 次
DThreadtasks=new DThread[max_num];
for(int i=0;i<max_num;i++){
long start=i*perLen;
RandomAccessFile currentPart=new RandomAccessFile(destFileName,"rwd");
currentPart.seek(start);
tasks[i]=new DThread(i,strUrl,currentPart,start,perLen,0);
tasks[i].start();
}
public class DThread extends Thread {
String strUrl=null;
URL url=null;
int id;
RandomAccessFile destFile=null;
long size=0;
long startPart;
long hasRead=0;
long startPos;
public DThread(int id,String src,RandomAccessFile destFile,long start,long length,long hasRead){
this.id=id;
this.strUrl=src;
this.destFile=destFile;
this.size=length;
this.startPart=start;
this.hasRead=hasRead;
this.startPos=this.startPart+this.hasRead;
}
public long getHasRead(){
return this.hasRead;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
// destFile.seek(startPos);
System.out.println("Thread-"+id+" started.");
Thread.sleep(1000);
url=new URL(strUrl);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setReadTimeout(50000);
conn.setRequestMethod("GET");
InputStream ins=conn.getInputStream();
ins.skip(startPos);
byte[] buffer = new byte[DTask.BUFFER_SIZE];
int read=0;
while(hasRead<size && (read=ins.read(buffer))!=-1){
destFile.write(buffer, 0, read);
hasRead+=read;
System.out.println("Thread-"+id+" has Read "+hasRead);
}
destFile.close();
ins.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
mkLogger logger=new mkLogger("DThread");
logger.log("Error URL:"+strUrl);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}