NOTE
Multithreaded Folder Size Statistics
Start three threads to calculate separately; use the final thread to aggregate the result.
This is a historical learning note and may contain outdated or incomplete understanding.
- Start three threads to calculate the folder sizes separately.
- Use the final thread to aggregate the result.
public class DirSizeStatistic
{
private static class DirSize
{
private Long size;
public DirSize(Long size)
{
this.size = size;
}
public Long getSize()
{
return size;
}
public void setSize(Long size)
{
this.size = size;
}
public synchronized void addSize(long size)
{
this.size += size;
}
}
private static class StatisticThread implements Runnable
{
private DirSize dirSize;
private CountDownLatch latch;
private String path;
public StatisticThread(DirSize dirSize, CountDownLatch latch, String path)
{
this.dirSize = dirSize;
this.latch = latch;
this.path = path;
}
@Override
public void run()
{
try
{
this.dirSize.addSize(FileUtils.sizeOf(new File(this.path)));
}finally
{
latch.countDown();
}
}
}
private static class StatisticAllThread implements Runnable
{
private DirSize dirSize;
private CountDownLatch latch;
public StatisticAllThread(DirSize dirSize, CountDownLatch latch)
{
this.dirSize = dirSize;
this.latch = latch;
}
@Override
public void run()
{
try
{
this.latch.await();
System.out.println(this.dirSize.getSize());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
CountDownLatch latch = new CountDownLatch(3);
DirSize dirSize = new DirSize(0L);
new Thread(new StatisticThread(dirSize, latch, "E:\\Example\\folder1")).start();
new Thread(new StatisticThread(dirSize, latch,"E:\\Example\\folder2")).start();
new Thread(new StatisticThread(dirSize, latch,"E:\\Example\\folder3")).start();
new Thread(new StatisticAllThread(dirSize, latch)).start();
}
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub