java使用线程下载多个文件

use*_*201 13 java multithreading

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

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

for (String name : fileNames){
    downloadFile(name, toPath);
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*art 35

你真的想使用ExecutorService而不是单独的线程,它更干净,可能性能更高,并且可以让你以后更容易地改变事物(线程数,线程名称等):

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)
Run Code Online (Sandbox Code Playgroud)

你班上的其他地方定义了实际的工作马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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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


mae*_*ics 5

是的,你当然可以在for循环中创建一个新线程.像这样的东西:

List<Thread> threads = new ArrayList<Thread>();
for (String name : fileNames) {
  Thread t = new Thread() {
    @Override public void run() { downloadFile(name, toPath); }
  };
  t.start();
  threads.add(t);
}
for (Thread t : threads) {
  t.join();
}
// Now all files are downloaded.
Run Code Online (Sandbox Code Playgroud)

您还应该考虑使用Executor,例如,在创建的线程池中Executors.newFixedThreadPool(int).