要求分析
例:定义三个线程来复制文件,先计算文件总大小,然后平均分配给三个线程,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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14631.html