java使用线程下载多个文件 [英] java download multiple files using threads

查看:67
本文介绍了java使用线程下载多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用线程下载与模式匹配的多个文件。该模式可以匹配1或5或10个差异大小的文件。

I am trying to download multiple files that matches a pattern using threads. The pattern could match 1 or 5 or 10 files of diff sizes.

为简单起见,我们可以说下载文件的实际代码是downloadFile()方法,而fileNames是与模式匹配的文件名列表。我如何使用线程执行此操作。每个线程只下载一个文件。是否可以在for循环中创建一个新线程。

lets say for simplicity sake the actual code that would download the file is in downloadFile() method and fileNames is the list of filenames that match the pattern. How do I do this using threads. Each thread will download only one file. Is it advisable to create a new thread inside the for loop.

for (String name : fileNames){
    downloadFile(name, toPath);
}


推荐答案

你真的想用一个 ExecutorService 而不是单独的线程,它更干净,可能更多performant将使您以后更容易更改(线程数,线程名称等):

You really want to use an ExecutorService instead of individual threads, it's much cleaner, likely more performant and will enable you to change things more easily later on (thread counts, thread names, etc.):

ExecutorService pool = Executors.newFixedThreadPool(10);
for (String name : fileNames) {
    pool.submit(new DownloadTask(name, toPath));
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// all tasks have now finished (unless an exception is thrown above)

在某处你班上的其他人定义实际工作马 DownloadTask

And somewhere else in your class define the actual work horse DownloadTask:

private static class DownloadTask implements Runnable {

    private String name;
    private final String toPath;

    public DownloadTask(String name, String toPath) {
        this.name = name;
        this.toPath = toPath;
    }

    @Override
    public void run() {
        // surround with try-catch if downloadFile() throws something
        downloadFile(name, toPath);
    }
}

shutdown()方法有一个非常混乱的名称,因为它将允许先前提交的任务在终止之前执行。 awaitTermination()声明需要处理的 InterruptedException

The shutdown() method has a very confusing name, because it "will allow previously submitted tasks to execute before terminating". awaitTermination() declares an InterruptedException you need to handle.

这篇关于java使用线程下载多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆