技能库--统计文件大小 + CountDownLatch(87)
2017-01-20 08:48
204 查看
使用countdo
4000
wnlatch工具
当pendingFileVisits (原子性线程安全的变量)中访问的文件个数为零时,通知主线程结束
结果:23秒 提速50% 比单线程
4000
wnlatch工具
当pendingFileVisits (原子性线程安全的变量)中访问的文件个数为零时,通知主线程结束
public class CountdownLatch0 { private ExecutorService service; final private AtomicLong pendingFileVisits = new AtomicLong(); final private AtomicLong totalSize = new AtomicLong(); final private CountDownLatch latch = new CountDownLatch(1); private void updateTotalSizeOfFilesInDir(final File file) { long fileSize = 0; if (file.isFile()) fileSize = file.length(); else { final File[] children = file.listFiles(); if (children != null) { for(final File child : children) { if (child.isFile()) fileSize += child.length(); else { pendingFileVisits.incrementAndGet(); service.execute(new Runnable() { public void run() { updateTotalSizeOfFilesInDir(child); } }); } } } } totalSize.addAndGet(fileSize);//共享变量 此处产生多个线程compete 堵塞 if(pendingFileVisits.decrementAndGet() == 0) latch.countDown(); } private long getTotalSizeOfFile(final String fileName) throws InterruptedException { service = Executors.newFixedThreadPool(100); pendingFileVisits.incrementAndGet(); try { updateTotalSizeOfFilesInDir(new File(fileName)); latch.await(100, TimeUnit.SECONDS); return totalSize.longValue(); } finally { service.shutdown(); } } public static void main(final String[] args) throws InterruptedException { final long start = System.nanoTime(); final long total = new CountdownLatch0() .getTotalSizeOfFile("C:\\Users"); final long end = System.nanoTime(); System.out.println("Total Size: " + total); System.out.println("Time taken: " + (end - start)/1.0e9); } }
结果:23秒 提速50% 比单线程
Total Size: 50315772180 Time taken: 23.029064337
相关文章推荐
- 技能库--统计文件大小 +Fork-Join(90)
- 统计目录和文件大小
- LoadRunner中如何验证下载的文件大小、统计下载时间、度量下载速度?
- hadoop 统计一个目录的文件大小
- PHP中统计目录中文件以及目录中目录的大小
- linux统计文件夹某一些文件的大小总和
- 日记 [2008年02月03日]统计目录和文件大小
- 编写一个\函数解决统计文件或目录大小并转换存储单位
- sharepoint 2007 统计所有网站集中视频文件的总大小
- java实现文件名,路径,日期,文件大小的统计并存入数据库
- awk算术运算一例:统计hdfs上某段时间内的文件大小
- 统计一个文本文件中大小英文字母出现的个数
- 【PHP】统计文件大小,以GB、MB、KB、B输出
- 统计文件大小,以GB、MB、KB、B输出
- aix察看根目录各文件和子目录大小,去除文件系统统计
- perl脚本之__分类统计某一目录下指定类型文件的大小
- awk算术运算一例:统计hdfs上某段时间内的文件大小
- du:统计目录(或文件)所占磁盘空间的大小
- 统计当前目录下的所有文件目录大小,不显示子目录与子文件
- awk算术运算一例:统计hdfs上某段时间内的文件大小