JAVA实现多线程复制同一个文件(非伪代码)

要求分析

例:定义三个线程来复制文件,先计算文件总大小,然后平均分配给三个线程,0-1000,1001-2000,2001-3000,类似这样,如果文件大小不能被三个线程平均处理,这里我用的是再次开启一个线程来复制,其实我觉得不太妥当,因为给定是三个线程来复制,所以我想是否可以用到线程池来解决这个问题,让复制完的线程进入线程池,继续处理剩余的文件。这里可以设置核心线程数为三,等待队列大小为一。但是多开启一个线程还是比开启线程池来的直接一点,除非有硬性要求,否则多开启一个线程来处理已经足够了。

代码实现一(多开启一个线程)

多开启一个线程来解决

public class Test1 {
    public static void main(String[] args) throws UnknownHostException, FileNotFoundException {
 File file = new File("D:\\Learning\\JAVA\\资料\\文档资料\\JVM方面的\\图文说明JVM垃圾回收-上篇.pdf");
        //获取文件总大小
        long totalLength = file.length();
        System.out.println(totalLength);
        //定义线程数
        long threadNum = 3;
        //平均每个线程复制的字节数
        long averNum = totalLength/threadNum;
        //开启多个线程复制文件
        for (long i = 0; i < threadNum; i++) {
            //计算出每个线程复制文件的起始位置和结束位置
            long start = i*averNum;
            long end = (i+1)*averNum-1;
            //循环开启线程
            System.out.println("线程"+i+"开始位置"+start+"结束位置"+end);
            new CopyFileThread(start,end,file,"D:\\demo.pdf").start();
        }
        if(totalLength%threadNum!=0){
            long start = threadNum*averNum;
            long end = totalLength;
            System.out.println("线程"+threadNum+"开始位置"+threadNum*averNum+"结束位置"+totalLength);
            new CopyFileThread(start,end,file,"D:\\demo.pdf").start();
        }
     }
 }

class CopyFileThread extends Thread{
    long start;
    long end;
    RandomAccessFile in = null;
    RandomAccessFile out = null;

    public CopyFileThread(long start, long end, File srcFile, String targetFile) throws FileNotFoundException {
        this.start = start;
        this.end = end;
        in = new RandomAccessFile(srcFile,"rw");
        out = new RandomAccessFile(targetFile,"rw");

    }

    @Override
    public void run() {
        //开始文件复制
        try {
            in.seek(start);
            out.seek(start);
            //out.seek(end);
            int len = 0;
            byte[] bytes = new byte[1024*8];
            while(start<end&&(len = in.read(bytes))!=-1){
                start+=len;
                out.write(bytes,0,len);
            }
           in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

测试结果

在这里插入图片描述在这里插入图片描述

代码实现二(线程池实现)

博主还未遇到硬性需求,就偷个懒不写啦,等遇到的时候,再来分享咯,如果有人特别需要的话,可以留言,我看到就来补充啦,愿我们都能成为下一个郭宇,hhhhhh

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值