您的位置:首页 > 其它

技能库--统计文件大小 + CountDownLatch(87)

2017-01-20 08:48 204 查看
使用countdo
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并发