多线程复制同一份文件

package club.calong.lawyer;
// 团   队: 风讯网络
// 后   端: Dopa
// 开发时间: 2021/7/25 15:06

import java.io.*;
import java.time.Duration;
import java.time.LocalDateTime;

public class ApplicationTest extends Thread {
    long begin;
    long end;
    RandomAccessFile sourceFile;
    RandomAccessFile targetFile;

    public ApplicationTest(long begin, long end, File file , String targetFilePath) throws IOException {
        this.begin = begin;
        this.end = end;
        this.sourceFile = new RandomAccessFile(file, "rw");
        this.targetFile = new RandomAccessFile(targetFilePath, "rw");
        sourceFile.seek(begin);
        targetFile.seek(begin);
    }

    @Override
    public void run() {
        byte[] bytes = new byte[1];
        try {
            while (begin<end&&sourceFile.read(bytes) != -1) {
                begin += 1;
                targetFile.write(bytes,0,1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                targetFile.close();
                sourceFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    
}

class Start {
    public static void main(String[] args) throws IOException, InterruptedException {
        File file=new File("C:\\TEST\\test.sql");
        int index = Runtime.getRuntime().availableProcessors()-4;
        long divisor = file.length() / index;
        LocalDateTime startTime=LocalDateTime.now();
        
        for (int i = 0; i < index+1; i++) {
            System.out.println((divisor * i) + "-----" + (divisor * (i + 1)));
          Thread thread= new ApplicationTest(divisor*i,divisor*(i+1),file, "C:\\TEST\\test44.sql");
          thread.setName("copy"+i);
          thread.join();
          thread.start();
        }
        
        LocalDateTime endTime=LocalDateTime.now();
        System.out.println(startTime);
        System.out.println(endTime);
        Duration duration=Duration.between(startTime, endTime);
        System.out.println(duration.toMillis());
        System.out.println(duration.toNanos());
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值