使用多线程下载的问题~

1.DownLoadThread
[code="java"]import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownLoadThread implements Runnable {
String url = "";
File file = null;
int startp;
int endp;
int i;

public DownLoadThread(String url, int startp, int endp, File file, int i) {
    this.url = url;
    this.file = file;
    this.startp = startp;
    this.endp = endp;
    this.i = i;

}

public void run() {
    try {
        System.out.println("第"+i+"个线程");
        URL downUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) downUrl
                .openConnection();
        InputStream is = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        byte buf[] = new byte[1024];
        int size = -1;
        int flag = 0;
        raf.seek(flag);
        //bis.skip(startp + 1);
        while ((size = bis.read(buf,0,1024)) > 0) {
            if ((startp + size) >= endp) {
                size = endp - startp;
            }
            raf.write(buf, 0, size);
            startp = startp + size;
            flag+=size;
        }
        bis.close();
        raf.close();
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}[/code]
2.TestDownLoad
[code="java"]public class TestDownLoad {

int i;


public void multiThreadDown(String url, int bytecount, int threadnum,int filelength) {

    while (i < threadnum) {
        int startp = bytecount * i;
        int endp = bytecount * (i + 1);
        File f = new File("C:\\123.jpg");
        DownLoadThread Dt = new DownLoadThread(url, startp, endp, f, i);
        new Thread(Dt).start();
        i++;
    }

}public static void main(String[] args) {

    TestDownLoad TD = new TestDownLoad();
    String     url= "http://hiphotos.baidu.com/myloveby2/pic/item/6e6b8bda7ed52e42d0164e8b.jpg";
    int bytecount = 0;
    int threadnum = 3;
    DownLoadRe dr = new DownLoadRe();
    int filelength = dr.getFileLength(url);
    if (filelength != -1) {
        bytecount = (filelength / threadnum);

    }

    TD.multiThreadDown(url,bytecount,threadnum,filelength);
}

}
[/code]

DownLoadRe dr = new DownLoadRe();
int filelength = dr.getFileLength(url);这个是用来计算mp3的长度的。
[size=medium]为什么下载的东西长度少很多,是拼接的问题吗?[/size]
[b]问题补充:[/b]
[code="java"]raf.seek(startp);

        while (startp < endp) {

            size = bis.read(buf, 0, 1024);
            if (size == -1)
                break;
            raf.write(buf, 0, size);
            startp = startp + size;

        }

[/code]

修改成这样吧,ok了

int flag = 0;

raf.seek(flag);

你这里一看就错了,每个线程都从文件头开始写,startp根本没起作用。
另外main方法
bytecount = (filelength / threadnum);

也有隐患,最好是
先用 filelength % threadnum 来判断是否需要舍入。
这代码抄的还是自己写的,低级错误很多。