java使用使用多线程和随机访问流模拟高速下载器

思路:
  1. 使用多线程和随机访问流,一个文件分俩半,一个线程负责第一个部分的内容,并且边读边写,另一个线程负责第二部分的内容,并且边读边写
  2. 代码中利用RandomAccessFile类型的对象 in和out,in负责读,out负责写,俩个线程对象中使用是同一对随即流对象(in out),注意加锁
代码和解释如下
public class Work6 {
    public static void main(String[] args) throws FileNotFoundException, InterruptedException {
        File file = new File("src/com/yzx/Work/day20/TestFileDir/poetry.txt");
        //获得文件长度
        long length = file.length();
        //文件可读可写
        RandomAccessFile in = new RandomAccessFile(file,"rw");
        RandomAccessFile out = new RandomAccessFile("src/com/yzx/Work/day20/TestFileDir/poetry.txt","rw");
        //构建线程
        Thread t1 = new XunLeiThread("第一个线程",in,out,0,length/2);
        Thread t2 = new XunLeiThread("第二个线程",in,out,length/2,length);
        //主线程休眠一会儿
        Thread.sleep(1000);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

class XunLeiThread extends Thread{
    RandomAccessFile in = null;
    RandomAccessFile out = null;
    long start;//记录文件起始位置
    long end;//记录文件终止位置

    public XunLeiThread(String name, RandomAccessFile in, RandomAccessFile out, long start, long end) {
        super(name);
        this.in = in;
        this.out = out;
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        //字节数组读取
        byte[] buff = new byte[1024];
        int len = -1;
        //只读一半
        while (start<end){
            //加锁
            synchronized (this.getClass()){
                try {
                	//移动游标
                    in.seek(start);
                    out.seek(start);
                    //每次只读指定长度
                    len = in.read(buff);
                    //如果最后读取的长度超过了一半文件大小
                    //好比:文件大小为 4000字节,一半就是end = 2000,每次读取1024
                    //第二次读取的时候 start = 1024,则继续读取的时候为 1024+1024>2000
                    //所以第二次要读取的长度就变为 end-start=2000-1024
                    if ((start+len)>end){
                        len = (int) (end-start);
                        out.write(buff,0,len);
                        System.out.println(name+"读取文件结束");
                        break;
                    }
                    out.write(buff,0,len);
                    //每次读取文件之后,游标向后移动
                    start = start+len;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(name+"读取文件结束");
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值