Package COM. downloadthreads; import Java. io. file; import Java. io. randomaccessfile; import Java. util. date;/** multithread download example ***/public class downloadmain {private long startpoint; private int threadnum = 5; private long filesize; private long currentpartsize; private file = NULL; private file file1 = NULL;/** open the target resource; create the target file and enable the thread */Public void download () throws exception {file1 = new file ("D: /test // test1.txt "); randomaccessfile file = new randomaccessfile (" D:/test // test.txt "," RW "); randomaccessfile RAF = new randomaccessfile (file1, "RW"); // sets the size of the received file. setlength (file. length (); RAF. close (); filesize = file. length (); currentpartsize = filesize/threadnum + 1; // For (INT I = 0; I <threadnum; I ++) {startpoint = I * currentpartsize; randomaccessfile RAFs = new randomaccessfile (file1, "RW"); RAFs. seek (startpoint); thread t = new downloadthread (startpoint, currentpartsize, RAFs, file); T. start (); system. out. println (T. getname () ;}} public static void main (string [] ARGs) throws exception {downloadmain main = new downloadmain (); system. out. println (new date (); main. download (); system. out. println (new date ());}}
package com.downloadthreads;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.RandomAccessFile;public class DownloadThread extends Thread{private long startpoint;private long currentpartsize;private RandomAccessFile rafs;private RandomAccessFile file;public DownloadThread(long startpoint, long currentpartsize,RandomAccessFile rafs, RandomAccessFile file) {super();this.startpoint = startpoint;this.currentpartsize = currentpartsize;this.rafs = rafs;this.file = file;}@Overridepublic void run() {int hasread;int lenth=0; byte[] b=new byte[1024]; try { file.skipBytes((int)startpoint);while(lenth<currentpartsize&&(hasread=file.read(b))>0){rafs.write(b);lenth+=hasread;}} catch (IOException e) {e.printStackTrace();}}}