niumoo / down-bit

一个 Java 实现的,多线程,断点续传下载器

Home Page:https://www.wdbyte.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

日志工具类,是否支持2个及以上文件同时断点续传呢.

rokeylv opened this issue · comments

`public class LogThread implements Callable {

public static AtomicLong LOCAL_FINISH_SIZE = new AtomicLong();
public static AtomicLong DOWNLOAD_SIZE = new AtomicLong();
public static AtomicLong DOWNLOAD_FINISH_THREAD = new AtomicLong();
private long httpFileContentLength;

public LogThread(long httpFileContentLength) {
    this.httpFileContentLength = httpFileContentLength;
}

@Override
public Boolean call() throws Exception {
    int[] downSizeArr = new int[5];
    int i = 0;
    double size = 0;
    double mb = 1024d * 1024d;
    // 文件总大小
    String httpFileSize = String.format("%.2f", httpFileContentLength / mb);
    while (DOWNLOAD_FINISH_THREAD.get() != DownloadMain.DOWNLOAD_THREAD_NUM) {
        double downloadSize = DOWNLOAD_SIZE.get();
        downSizeArr[++i % 5] = Double.valueOf(downloadSize - size).intValue();
        size = downloadSize;

        // 每秒速度
        double fiveSecDownloadSize = Arrays.stream(downSizeArr).sum();
        int speed = (int)((fiveSecDownloadSize / 1024d) / (i < 5d ? i : 5d));

        // 剩余时间
        double surplusSize = httpFileContentLength - downloadSize - LOCAL_FINISH_SIZE.get();
        String surplusTime = String.format("%.1f", surplusSize / 1024d / speed);
        if (surplusTime.equals("Infinity")) {
            surplusTime = "-";
        }

        // 已下大小
        String currentFileSize = String.format("%.2f", downloadSize / mb + LOCAL_FINISH_SIZE.get() / mb);
        String speedLog = String.format("> 已下载 %smb/%smb,速度 %skb/s,剩余时间 %ss", currentFileSize, httpFileSize, speed, surplusTime);
        System.out.print("\r");
        System.out.print(speedLog);
        Thread.sleep(1000);
    }
    System.out.println();
    return true;
}

}`

本人多线程经验不是特别丰富.这类将一些成员变量记录为静态的,如果2个文件都在进行断点续传下载,这个变量(LOCAL_FINISH_SIZE)是否会被设置2次

不好意思,才看到。
回到问题哈,这个工具写的有点久了。这里的 LOCAL_FINISH_SIZE 是一个 AtomicLong 类型的实例,对于 AtomicLong 类型,它本身就是一个线程安全的类,可以正常的用于多线程,且增加和减少计数都是原子操作,不会因为多线程调用而发生意料之外的情况哈。🍔🍔