在多线程下载中限制下载速度

时间:2015-06-29 21:07:49

标签: java multithreading stream

我试图在多线程下载器应用程序(如IDM)中限制下载速度。到目前为止,我已经在this answer的帮助下完成了这项工作,但它不起作用,我不明白为什么。这是我的包装类:

public class DownloadStream
{
    InputStream in;
    long timestamp;
    static int counter = 0;
    static int INTERVAL = 1000;
    static int LIMIT;
    static boolean speedLimited;

    public DownloadStream(InputStream stream, boolean speedLimited, int kbytesPerSecond)
    {
        LIMIT = kbytesPerSecond * 1000;
        this.speedLimited = speedLimited;
        in = stream;
    }

    public int read(byte[] buffer) throws IOException
    {
        if(!speedLimited)
            return in.read(buffer);

        check();

        int res = in.read(buffer);
        if (res >= 0) {
            counter += res;
        }
        return res;
    }

    public synchronized void check()
    {
        if (counter > LIMIT)
        {
            long now = System.currentTimeMillis();
            if (timestamp + INTERVAL >= now) {
                try
                {
                    Thread.sleep(timestamp + INTERVAL - now);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            timestamp = now;
            counter -= LIMIT;
        }
    }
}

我在每个下载程序线程中都像InputStream一样使用它:

byte[] buffer = new byte[4096];
while((length = input.read(buffer)) != -1)
{
    output.write(buffer,0,length);
}

如果我以8个线程输入kbytesPerSecond,则下载速度可达每秒16千字节。我已经counter静态以防止这种情况发生,但它不起作用。

0 个答案:

没有答案