ExecutorService多线程扫描全盘路径

来源:互联网 发布:淘宝店铺最迟多久发货 编辑:程序博客网 时间:2024/06/02 13:15

多线程能节省好多时间。

        List<File> rootDirs = new ArrayList<File>();        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime()                .availableProcessors());        for (String item : mStoragePaths) {            File file = new File(item);            if (IdentificationUtil.getStorageState(mWeakContext.get(),                    file.getAbsolutePath()).equals(Environment.MEDIA_MOUNTED)) {                File[] files = new File(item).listFiles();                if (files != null && files.length != 0) {                    rootDirs.addAll(Arrays.asList(new File(item).listFiles()));                }            }        }        for (final File file : rootDirs) {            executorService.execute(new Runnable() {                @Override                public void run() {                    scanDictionary(file, 2);                }            });        }        executorService.shutdown();        try {            executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);        } catch (InterruptedException e) {            e.printStackTrace();        }

其中,Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());是获取CPU个数线程的线程池。


executorService.execute()执行的时候,只要有线程空闲就会执行任务。


shutdown()方法不是一个阻塞方法,本身执行很快,执行完后线程池仍可能处于运行中。


awaitTermination()方法是一个阻塞方法,它必须等线程池退出后才会结束自身。

0 0
原创粉丝点击