NOTE

多线程统计文件夹大小

开三个线程分别统计,最后一个线程汇总。

Java创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

  • 开三个线程分别统计
  • 最后一个线程汇总
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();

    }
}

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看